I've done a UDP socket server in C. The server works properly only if the packets are send to 127.0.0.1. I'm trying to test it with packet sender, and I want to open a socket at the address 192.168.231.54. Anyway, if I write this address in the code, I receive an error ("Cannot assign requested address"), and this error appears for each single address different from 127.0.0.1. I want to open a socket to 192.168.231.54 and I want to send packets to this address with Packet Sender.
Here is the server code:
//*********SOCKET OPENING**************
int fd;
struct sockaddr_in serveraddr, cliaddr;
if ( (fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror( "socket failed" );
exit(EXIT_FAILURE);
}
memset( &serveraddr, 0, sizeof(serveraddr) );
memset(&cliaddr, 0, sizeof(cliaddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(50037);
serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
if ( bind(fd, (const struct sockaddr *)&serveraddr, sizeof(serveraddr)) < 0 ) {
perror( "bind failed" );
exit(EXIT_FAILURE);
}
else{
perror("socket opened");
}
//Receiving data into hex_array array
char hex_array[lenght];
int len;
len = sizeof(cliaddr);
int n = recvfrom(fd, (uint8_t *)hex_array, lenght, NULL, ( struct sockaddr *) &cliaddr, &len);
//Printing of the received data on the socket
printf("START DEBUG:\n");
printf("%s\n", hex_array);
printf("END DEBUG.\n");
The address you bind the socket to has to actually be your computer's IP address. You can't just pick a random address.
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.