CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 9 of 9
  1. #1
    Join Date
    Oct 2007
    Posts
    9

    UDP Socket between C++ and Python

    Hi there,

    Appologise if i have posted in the wrong forum but since it uses both C++ and Python i thought that i would post here.

    Basically i have a program which i want to send a string of data from C++ to Python in real time i.e. when the C++ program is being executed. My program compiles with visual studio (i am on a Windows 7 64bit system) and the program runs but the socket between C++ and python does not seem to work, the Python file just crashes as though it is listening but not picking anything up.

    I use the Microsoft loopback adapter and i transmit the packet between both on the ip address which i have been given for the loopback adapter through windows:

    Autoconfiguration IPv4: 169.254.94.247 i.e. the ip address for the loopback adapter

    Can somebody tell me if the packet in the C++ code below should be sent ok to Python via a socket? I'm thinking that the Python code on the other end is fine and should pick up the packet but as i say, for some reason the Python just hangs as though it is waiting for a packet to come. I am using winsock2 library to perform this. The two programs are to be ran on the same machine.

    C++ code
    const int ECHOMAX = 255; // Longest string to echo


    SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

    sockaddr_in addr;

    struct sockaddr_in server;
    unsigned short sourcePort=5000; // Port of datagram source

    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr("169.254.94.247");
    server.sin_port=htons(sourcePort);

    char echoBuffer[ECHOMAX]; // Buffer for echo string
    int recvMsgSize; // Size of received message

    //csMyData is the variable which holds the string to send via the socket to python
    strcpy (echoBuffer,m_csMyData);
    recvMsgSize = strlen (echoBuffer);
    echoBuffer[recvMsgSize] = '\0';
    sendto(sock, echoBuffer, recvMsgSize, NULL, (SOCKADDR*)&addr, sizeof(struct sockaddr_in));


    Here is my python at the other end:

    HOST = "169.254.94.247"
    PORT = 5000

    mySocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    mySocket.bind ( (HOST, PORT))

    packet, address = mySocket.recvfrom(1024) #the code seems to be constantly stuck in a loop once this is added


    As you can see, both use the same IP address and port numbers and so i am quite stumped. I am quite new to socket programming and so if there is any way i can see if it has been sent then that would be great. If you think i could write my code in a different way then that would be good if i could see the right way to write it in C++

    Many thanks and if somebody could help me notice why my socket is now working and why it doesn't seem to connect to it in Python then that would be great as it just seems to hang in Python at the moment.

    Mark
    Last edited by Sharkadder; August 15th, 2013 at 02:59 AM.

  2. #2
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,395

    Re: UDP Socket between C++ and Python

    1. Please, use Code tags when you post code snippets.

    2.
    Quote Originally Posted by Sharkadder View Post
    Code:
    	packet, address = mySocket.recvfrom(1024) #the code seems to be constantly stuck in a loop once this is added
    What does this line mean? What is 1024?
    Victor Nijegorodov

  3. #3
    Join Date
    Oct 2007
    Posts
    9

    Re: UDP Socket between C++ and Python

    Quote Originally Posted by VictorN View Post
    1. Please, use Code tags when you post code snippets.

    2. What does this line mean? What is 1024?
    Hi there and appologies for not using the snippets. The 1024 is the size of the message in bytes which it can handle. Since i am only sending one string of data it should be fine. Does my C++ look ok or is there a way i can test if the actual message has been sent over to Python? As i say, the C++ program doesn't spit out any errors in the console or anything. Any help with it would be great for me to get it working.

    Many thanks,

    Mark

  4. #4
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,395

    Re: UDP Socket between C++ and Python

    Quote Originally Posted by Sharkadder View Post
    Does my C++ look ok or is there a way i can test if the actual message has been sent over to Python? As i say, the C++ program doesn't spit out any errors in the console or anything.
    Did you debug your C++ code? Do you check the return values of all the socket functions used there?
    Victor Nijegorodov

  5. #5
    VictorN's Avatar
    VictorN is offline Super Moderator Power Poster
    Join Date
    Jan 2003
    Location
    Hanover Germany
    Posts
    20,395

    Re: UDP Socket between C++ and Python

    Quote Originally Posted by Sharkadder View Post
    Does my C++ look ok or is there a way i can test if the actual message has been sent over to Python?
    Have you posted the complete code?
    Do you close the connection in the client after sending data?
    Victor Nijegorodov

  6. #6
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: UDP Socket between C++ and Python

    As i say, the C++ program doesn't spit out any errors in the console or anything.
    That's not how c++ programs work unless you have coded the program to do this. Any call to a function that returns data should have the return value checked to make sure that the function has worked properly or not.

    For sendto see
    http://msdn.microsoft.com/en-us/libr...=vs.85%29.aspx

    I suggest you amend your c++ code to check function return codes for errors and then see what happens. If the program still does not work then you will know which c++ function is failling and the error code.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  7. #7
    Join Date
    Oct 2007
    Posts
    9

    Re: UDP Socket between C++ and Python

    Quote Originally Posted by 2kaud View Post
    That's not how c++ programs work unless you have coded the program to do this. Any call to a function that returns data should have the return value checked to make sure that the function has worked properly or not.

    For sendto see
    http://msdn.microsoft.com/en-us/libr...=vs.85%29.aspx

    I suggest you amend your c++ code to check function return codes for errors and then see what happens. If the program still does not work then you will know which c++ function is failling and the error code.
    Ok sorry to be a right pain but yeah, i last programmed something in c++ 4 years ago and have not really touched the language since, in fact the last thing i did on sockets and pipes was in standard C and over the years i have forgotten it and so excuse my "dumbness" if you like.

    The reason i am doing this is because an application which has been pre-made was made in C++ to get data from an external device. I just need to get a string of data from it to Python so that i can code the rest in python once i have got this data.

    Basically i decided to run a console application and put all of the code into it (to make it easier for both me and yourselves); for some reason the socket is not even starting and i have the error code below:

    Socket failed with error: 0

    the error is coming from this part of the code after i put the break points on and check:

    Code:
        if (sock == INVALID_SOCKET) {
            wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
    		//MessageBoxW(NULL,L"socket failed with error: %ld\n",L"socket failed with error: %ld\n",MB_OK);
            WSACleanup();
    		return 1;
        }
    Here is my full new console application code:

    Code:
    // sockettestconsole.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #ifndef UNICODE
    #define UNICODE
    #endif
    #define WIN32_LEAN_AND_MEAN
    #include <string>
    #include "stdafx.h"
    #include <stdio.h>
    #include <winsock2.h>
    #include "PracticalSocket.h"
    #include <ws2tcpip.h>
    #include <iostream>
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	#pragma comment(lib, "Ws2_32.lib")
    
    	const int ECHOMAX = 255; // Longest string to echo
    	int iResult;
    	WSADATA wsaData;
    	SOCKET sock = INVALID_SOCKET;
    	sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    	
        iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
        if (iResult != NO_ERROR) {
            wprintf(L"WSAStartup failed with error: %d\n", iResult);
            return 1;
        }
    
        if (sock == INVALID_SOCKET) {
            wprintf(L"socket failed with error: %ld\n", WSAGetLastError());
    		//MessageBoxW(NULL,L"socket failed with error: %ld\n",L"socket failed with error: %ld\n",MB_OK);
            WSACleanup();
    		return 1;
        }
    
    	sockaddr_in server;
    
        //struct sockaddr_in server;
    	unsigned short sourcePort=5000; // Port of datagram source
    
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr("169.254.94.247");
        server.sin_port=htons(sourcePort);
    
    	char echoBuffer[ECHOMAX]; // Buffer for echo string
    	int recvMsgSize; // Size of received message
    	//string sourceAddress="169.254.94.247"; // Address of datagram source
    	
    	strcpy (echoBuffer,"hello");
    	recvMsgSize = strlen (echoBuffer);
    	echoBuffer[recvMsgSize] = '\0';
    	iResult = sendto(sock, echoBuffer, recvMsgSize, 0, (SOCKADDR*)&server, sizeof(server));
    	//End of Sending tracking data
    
        if (iResult == SOCKET_ERROR) {
            wprintf(L"sendto failed with error: %d\n", WSAGetLastError());
            closesocket(sock);
            WSACleanup();
    		return 1;
        }
        //---------------------------------------------
        // When the application is finished sending, close the socket.
        wprintf(L"Finished sending. Closing socket.\n");
        iResult = closesocket(sock);
        if (iResult == SOCKET_ERROR) {
            wprintf(L"closesocket failed with error: %d\n", WSAGetLastError());
            WSACleanup();
            return 1;
    	}
        //---------------------------------------------
        // Clean up and quit.
        wprintf(L"Exiting.\n");
        WSACleanup();
    	return 0;
    }
    Anybody got any ideas? I am basically just writing the string "hello" now through the socket and it is not working. I have tried launching the python program first and then the c++ one but the Python program still hangs as though it is waiting for something.

    Many thanks,

    Mark

  8. #8
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,822

    Re: UDP Socket between C++ and Python

    According to MSDN documentation, a successful call to WSAStartup must occur before calling socket.

    http://msdn.microsoft.com/en-us/libr...=vs.85%29.aspx
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  9. #9
    Join Date
    Oct 2007
    Posts
    9

    Re: UDP Socket between C++ and Python

    Quote Originally Posted by 2kaud View Post
    According to MSDN documentation, a successful call to WSAStartup must occur before calling socket.

    http://msdn.microsoft.com/en-us/libr...=vs.85%29.aspx
    Dudeand the rest you are a legend, i know that you only led me to some Microsoft reference library websites but my socket is now working. All i did was move the WSAStatup above the socket initialisation in my previous code and therefore it worked :-).

    I have also added in all of the error checks too; in python i would normally use try and catch blocks but it's nice to know how to achieve a similar effect in C++. The python now picks up the string and i can use this data from within Python now.

    Many thanks for all of your help, going through the basic and the modifying it for my need seemed to really help my cause.

    Problem now solved :-).

    Mark

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured