简体   繁体   中英

Socket : no data on recv()

I have an outside equipment that is suppose to send datas every second to my program computer (under linux). The documentation of this equipment says : Ethernet interface with a fixed IP address of 192.168.0.40 The UDP ports used for the Ethernet interface is 4230 Destination : 192.168.0.20

So i tried to write the simpliest possible program to read these datas. My linux machine IP is set to 192.168.0.20 :

#define PORT 4230   
#define BUFSIZE 72 
struct sockaddr_in myaddr; /* our address */ 
struct sockaddr_in remaddr; /* remote address */ 
socklen_t addrlen = sizeof(remaddr); /* length of addresses */ 
int recvlen; /* # bytes received */ 
int fd; /* our socket */ 
unsigned char buf[BUFSIZE]; /* receive buffer */

/* create a UDP socket */ 
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) 
{ perror("cannot create socket\n"); return 0; } /* bind the socket to any valid IP address and a specific port */ 

 memset((char *)&myaddr, 0, sizeof(myaddr)); 
 myaddr.sin_family = AF_INET; 
 myaddr.sin_addr.s_addr = htonl(INADDR_ANY); 
 myaddr.sin_port = htons(PORT);

 if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) 
 { perror("bind failed"); return 0; } 

 /* now loop, receiving data and printing what we received */ 
 for (;;) 
{ 
    printf("waiting on port %d\n", PORT); 
    recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen); 
    printf("received %d bytes\n", recvlen); 
    if (recvlen > 0) 
    {
    buf[recvlen] = 0; 
    printf("received message: \"%s\"\n", buf); 
    } 
}

But i'm blocked at recvfrom(), never receiving datas ... What i'm doing wrong ? I tried to change INADDR_ANY to the right IP but still the same ...

Thank you.

EDIT/UPDATE : Using wireshark I have more information about the UDP packet from the outside equipment : Source 192.168.0.40 Destination 192.168.0.20 Source port 4230 Dest port 2430 Maybe i need to precise the dest port on the code ? But i don't know where and how to do this ...

The packet is destined for port 2430 , but your program is waiting for input on port 4230 (set with the PORT macro in your code).

The port should be the port you want input to be received on, not the source port on the other end of the communication.

So change the PORT macro to be 2430 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM