August 15th, 2013, 02:56 AM
UDP Socket between C++ and Python
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.
const int ECHOMAX = 255; // Longest string to echo
SOCKET sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
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");
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
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.
Last edited by Sharkadder; August 15th, 2013 at 02:59 AM.
Click Here to Expand Forum to Full Width
This is a CodeGuru survey question.