Sending and receiving UDP packets through NAT - c

I've been fiddling with this for a bit now. I have a server with a static IP address and a client sitting behind a consumer grade NAT (read a router provided by my ISP).
I'm trying to send a message, using UDP to the server and then receiving a response on the same socket. I have tried in a variety of languages, but just for the sake of it, here is my C version. I'm not sure if this a code problem or a machine configuration.
The message to the server goes through just fine, but the client never receives the response.
Client:
// Client side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define MAXLINE 1024
// Driver code
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "Hello from client";
struct sockaddr_in servaddr;
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
// Filling server information
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
// servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_addr.s_addr = inet_addr("87.118.127.66");
int n, len;
sendto(sockfd, (const char *)hello, strlen(hello),
MSG_CONFIRM, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
printf("Hello message sent.\n");
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
MSG_WAITALL, (struct sockaddr *) &servaddr,
&len);
buffer[n] = '\0';
printf("Server : %s\n", buffer);
close(sockfd);
return 0;
}
Server:
// Server side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define MAXLINE 1024
// Driver code
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "Hello from server";
struct sockaddr_in servaddr, cliaddr;
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
memset(&cliaddr, 0, sizeof(cliaddr));
// Filling server information
servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// Bind the socket with the server address
if ( bind(sockfd, (const struct sockaddr *)&servaddr,
sizeof(servaddr)) < 0 )
{
perror("bind failed");
exit(EXIT_FAILURE);
}
int len, n;
len = sizeof(cliaddr); //len is value/resuslt
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
MSG_WAITALL, ( struct sockaddr *) &cliaddr,
&len);
buffer[n] = '\0';
printf("Client : %s\n", buffer);
sendto(sockfd, (const char *)hello, strlen(hello),
MSG_CONFIRM, (const struct sockaddr *) &cliaddr,
len);
printf("Hello message sent.\n");
return 0;
}

UDP is a transport protocol and transport protocols carry a port. As you are working on this layer, the port has to be known/specified. But that is just not the case for recvfrom in your client code. It does not know from which port it should return the messages. Therefore you have to call bind and or connect in your client code.

Related

Infinite waiting during recvfrom() UDP server and client

I'm trying to learn UDP on C.
My goal is to send a message in console, in the client consol to the server, and sending the exact same message from the server to the client.
When I send a message from client to server, I do receive it, but the opposit is not working, and the waiting is infinite.
I don't have any problem in console.
The weird thing is that i'm using the exact same methode to send both messages.
Here's my client, Thanks to everyone helping me :)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define BUFSIZE 4096
// Driver code
int main(int argc, char *argv[]) {
char buffer[BUFSIZE];
struct sockaddr_in servaddr, cliaddr;
int len, n;
char *adresse= argv[1];
if (argc<1){
perror("nb args not enough");
exit(EXIT_FAILURE);
}
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(adresse);
servaddr.sin_port = htons(PORT);
// Socket()
int udp_server = socket(AF_INET, SOCK_DGRAM, 0) ;
if(udp_server<0){
perror("socket creation failed \n");
exit(EXIT_FAILURE);
}
// Bind())
int errBind = bind(udp_server, (const struct sockaddr *)&servaddr, sizeof(servaddr));
if(errBind<0){
perror("errBind \n" );
exit(EXIT_FAILURE);
}
// recvfrom()
n = recvfrom(udp_server, (char *)buffer, BUFSIZE,0, ( struct sockaddr *) &cliaddr,&len);
if (n<0){
perror("recvfrom error\n" );
exit(EXIT_FAILURE);
}
buffer[n] = '\0';
printf("CLIENT: %s\n", buffer);
char *message ="caca";
sendto(udp_server, (const char *)message, strlen(message),
0, (const struct sockaddr *) &cliaddr,
len);
close(udp_server);
//////////////////////////This part below is never reached
printf("end");
return 0;
}
Also here's my server:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define BUFSIZE 4096
// Driver code
int main(int argc, char *argv[]) {
char buffer[BUFSIZE];
// char *message = "AAAAAAAAAAAAAAAAAA";
struct sockaddr_in servaddr, cliaddr;
int len, n;
char *adresse= argv[1];
if (argc<1){
perror("nombre d'arguments insuffisents, veuillez entrer :\n ./serveur port_serveur \n");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(adresse);
// servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// Socket()
int udp_server = socket(AF_INET, SOCK_DGRAM, 0) ;
if(udp_server<0){
perror("socket creation failed \n");
exit(EXIT_FAILURE);
}
// Bind())
int errBind = bind(udp_server, (const struct sockaddr *)&servaddr, sizeof(servaddr));
if(errBind<0){
perror("errBind \n" );
exit(EXIT_FAILURE);
}
// recvfrom()
n = recvfrom(udp_server, (char *)buffer, BUFSIZE,0, ( struct sockaddr *) &cliaddr,&len);
if (n<0){
perror("recvfrom error\n" );
exit(EXIT_FAILURE);
}
buffer[n] = '\0';
printf("CLIENT: %s\n", buffer);
int l = sendto(udp_server, (const char *)buffer, strlen(buffer),
0, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
close(udp_server);
printf("end");
//////////////// This is reached
return 0;
}
There are several issues. The main issue is that both the client and server first tries to receive, then send. Thus they cannot both receive the message from the other party. Also, the client need not explicitly bind the socket.
In principle, the client must know the server address, but the server does not know the client address. Hence, the flow of communication must be that the client first sends a message to the server which will make the client known to the server. The server can then send a message to the address of the client.
In summary, the server should:
Create socket
Bind socket
Wait for message (recvfrom())
Send message to sender of the received message (sendto())
Close socket
The client should:
Create socket
Send message to the server (sendto())
Wait for message (recvfrom())
Close socket

Only one of two UDP listeners receives message

I'm trying to extend the example from here, to having to services receiving the same message from the same UDP port.
From this question, I understand that I should use SO_REUSEADDR to avoid the error of "address already in use". I have one client sending a "hello" message om port 8080 and two identical services, which simply prints out the received message from the port. SO_REUSEADDR solved the problem of using the same address, however only one of the services receives and prints out the message, while the other keep waiting.
Would it not be possible to have the same message received by both services?
The client:
// Client side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define MAXLINE 1024
// Driver code
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "Hello from client";
struct sockaddr_in servaddr;
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
// Filling server information
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = INADDR_ANY;
int n, len;
sendto(sockfd, (const char *)hello, strlen(hello),
MSG_CONFIRM, (const struct sockaddr *) &servaddr,
sizeof(servaddr));
printf("Hello message sent.\n");
close(sockfd);
return 0;
}
One of the two identical services:
// Server side implementation of UDP client-server model
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 8080
#define MAXLINE 1024
// Driver code
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "Hello from server";
struct sockaddr_in servaddr, cliaddr;
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
int reuse = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");
#ifdef SO_REUSEPORT
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEPORT) failed");
#endif
memset(&servaddr, 0, sizeof(servaddr));
memset(&cliaddr, 0, sizeof(cliaddr));
// Filling server information
servaddr.sin_family = AF_INET; // IPv4
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// Bind the socket with the server address
if ( bind(sockfd, (const struct sockaddr *)&servaddr,
sizeof(servaddr)) < 0 )
{
perror("bind failed");
exit(EXIT_FAILURE);
}
int len, n;
len = sizeof(cliaddr); //len is value/resuslt
n = recvfrom(sockfd, (char *)buffer, MAXLINE,
MSG_WAITALL, ( struct sockaddr *) &cliaddr,
&len);
buffer[n] = '\0';
printf("Client : %s\n", buffer);
return 0;
}
I think that Sockets act like a queue to your application. Each message received from the network gets placed in that queue, and applications calling recv() or recvfrom() pop messages off of that queue.
The two clients using the same UDP port will share the same queue. I think calling recvfrom() on one client will pop a message off of the queue for that client, and make that message unavailable for the other client.
I think that generally the best approach is to have a one-to-one relationship between clients and sockets.
But, you're curious and really want the message to be available for both clients, you could experiment with passing the MSG_PEEK flag to recvfrom(). That flag changes recvfrom() to not consume the next message from the socket queue, so the other client could also receive it.

Not able to send data packets over UDP

This is the code I used for Data transfer over UDP network
// server program for udp connection
#include <stdio.h>
#include <strings.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#define PORT xxxx
#define MAXLINE 1000
// Driver code
int main()
{
char buffer[100];
char *message = "Hello Client";
int listenfd, len;
struct sockaddr_in servaddr, cliaddr;
bzero(&servaddr, sizeof(servaddr));
// Create a UDP Socket
listenfd = socket(AF_INET, SOCK_DGRAM, 0);
servaddr.sin_addr.s_addr = inet_addr("192.168.xx.xx"); //htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
servaddr.sin_family = AF_INET;
// bind server address to socket descriptor
bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr));
//receive the datagram
while(1){
len = sizeof(cliaddr);
int n = recvfrom(listenfd, buffer, sizeof(buffer),
0, (struct sockaddr*)&cliaddr,&len); //receive message from server
buffer[n] = '\0';
puts(buffer);
// send the response
sendto(listenfd, message, strlen(message), 0,
(struct sockaddr*)&cliaddr, sizeof(cliaddr));
}
}
this is my code which runs perfectly with recvfrom and sendto functions over there.
but when I try to execute only sendto function just to only send data over UDP network. It stops working
while(1){
len = sizeof(cliaddr);
/*int n = recvfrom(listenfd, buffer, sizeof(buffer),
0, (struct sockaddr*)&cliaddr,&len); //receive message from server
buffer[n] = '\0';
puts(buffer);*/
// send the response
sendto(listenfd, message, strlen(message), 0,
(struct sockaddr*)&cliaddr, sizeof(cliaddr));
}
after doing this my network stop sending data to client device.
What should I do to overcome this issue?
anyone please help me!

sockets programming: sending and receiving different data to different clients in C

I have written a basic client server code in c socket programming using the TCP/IP protocol but i cant figure out how to make it connect to different clients and send/receive different data to and from them as a function to the client (meaning if its the first client send him that data and if its that client send him the other data) and so on.
This is the only results i have found were sending the same data to different clients.
Current Server:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
int main() {
char server_message[100] = {0};
int server_socket = 0;
int client_socket = 0;
struct sockaddr_in server_address;
server_socket = socket(AF_INET, SOCK_STREAM, 0);
server_address.sin_family = AF_INET;
server_address.sin_port = htons(9002);
server_address.sin_addr.s_addr = INADDR_ANY;
// bind the socket to our specified IP and port
bind(server_socket, (struct sockaddr*) &server_address, sizeof(server_address));
listen(server_socket, 2);
client_socket = accept(server_socket, NULL, NULL);
printf("Please enter a massage:");
fgets(server_message, 100, stdin);
send(client_socket, server_message, sizeof(server_message), 0);
close(server_socket);
return 0;
}
By using original code from geeksforgeeks and Myst comment we can solve it.
You have one server that serves on local host 127.0.0.1, and can have multiple clients for this example i assume 5 clients are enough.
Run server once, and run many client to connect seprately to that server.
Server.c
// Server side C/C++ program to demonstrate Socket programming
#include <unistd.h>
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <string.h>
#define PORT 8080
#define STRING_SIZE 100
#define BUFFER_SIZE 100
int main(int argc, char const *argv[])
{
int server_fd, new_socket[5], valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from server";
// Creating socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// Forcefully attaching socket to the port 8080
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,
&opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( PORT );
// Forcefully attaching socket to the port 8080
if (bind(server_fd, (struct sockaddr *)&address,
sizeof(address))<0)
{
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
for (int i=0;i<5;i++){
if ((new_socket[i] = accept(server_fd, (struct sockaddr *)&address,
(socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
valread = read(new_socket[i], buffer, 1024);
printf("%s\n", buffer);
char send_buf[STRING_SIZE] = "hello";
char buf[BUFFER_SIZE]={0};
sprintf(buf, "%d", i);
strcat(send_buf, buf);
send(new_socket[i], send_buf, strlen(send_buf), 0);
//printf("Hello message sent\n");
}
return 0;
}
Client.c
// Client side C/C++ program to demonstrate Socket programming
#include <stdio.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#define PORT 8080
int main(int argc, char const *argv[])
{
int sock = 0, valread;
struct sockaddr_in serv_addr;
char *hello = "Hello from client";
char buffer[1024] = {0};
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Socket creation error \n");
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(PORT);
// Convert IPv4 and IPv6 addresses from text to binary form
if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr)<=0)
{
printf("\nInvalid address/ Address not supported \n");
return -1;
}
if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nConnection Failed \n");
return -1;
}
send(sock , hello , strlen(hello) , 0 );
//printf("Hello message sent\n");
valread = read( sock , buffer, 1024);
printf("%s\n", buffer);
return 0;
}
Run
After compiling codes with gcc client.c -o client and gcc server.c -o server
Open one terminal for server and start server by run ./server.
Now you can connect many client [up to 5] to it by running ./client.

Problem sending msg to UDPClient on windows from UDPServer on linux

I have the UDPServer program running on linux and UDPClient program running on windows 10.
Note: In the UDP client program you have to add the linux server IP in the hash define.
Compilation on windows: gcc -Wall -o UDPClient UDPClient.c -lws2_32
Problem
UDPServer receives msg from UDP client and replies back. But the UDPClient on windows doesnt receive the msg from windows.
UDPServer.c (on linux)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define PORT 6200
#define MAXLINE 1024
int main() {
int sockfd;
char buffer[MAXLINE];
char *hello = "Hello from server";
struct sockaddr_in servaddr, cliaddr;
int n;
socklen_t from_len = sizeof(struct sockaddr);
socklen_t to_len = sizeof(struct sockaddr);
// Creating socket file descriptor
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
memset(&servaddr, 0, sizeof(servaddr));
memset(&cliaddr, 0, sizeof(cliaddr));
// Filling server information
servaddr.sin_family = AF_INET; // IPv4
//servaddr.sin_addr.s_addr = inet_addr(IP_ADDR); ;
servaddr.sin_addr.s_addr = INADDR_ANY;
servaddr.sin_port = htons(PORT);
// Bind the socket with the server address
if ( bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) < 0 )
{
perror("bind failed");
exit(EXIT_FAILURE);
}
n = recvfrom(sockfd, (char *)buffer, MAXLINE, 0, ( struct sockaddr *) &cliaddr, &from_len);
buffer[n] = '\0';
printf("Client : %s ; IP = %s ; Port = %d\n", buffer,inet_ntoa(cliaddr.sin_addr), ntohs(cliaddr.sin_port));
sendto(sockfd, (const char *)hello, strlen(hello), MSG_CONFIRM, (const struct sockaddr *) &cliaddr, to_len);
printf("Hello message sent.\n");
return 0;
}
// UDP client (on windows)
#include<stdio.h>
#include<winsock2.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <inttypes.h>
#define PORT 6200
#define IP_ADDR "xx.xx.xx.xx" //Add the linux server IP
#define BUF_SIZE 1024
/* Compilation: gcc -Wall -o UDPClient UDPClient.c -lws2_32 */
int SetupWinSock()
{
WSADATA wsa;
//printf("SetupWinSock: Initializing socket system\n");
if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
{
printf("SetupWinSock: Failed. Error Code : %d",WSAGetLastError());
return -1;
}
//printf("SetupWinSock: Initialization complete\n");
return 0;
}
SOCKET CreateUDPSocket()
{
SOCKET udpSocket;
if((udpSocket = socket(AF_INET , SOCK_DGRAM , IPPROTO_UDP )) == INVALID_SOCKET)
{
printf("CreateUDPSocket: Failed to create socket : %d" , WSAGetLastError());
return -1;
}
else
{
//printf("CreateUDPSocket: Socket creation successful\n");
}
return udpSocket;
}
int main() {
char buffer[BUF_SIZE];
char *hello = "Hello from client";
struct sockaddr_in servaddr, localAddr;
SOCKET udpSocket;
int n, len;
SetupWinSock();
// Creating socket file descriptor
udpSocket = CreateUDPSocket();
memset(&servaddr, 0, sizeof(servaddr));
// Server info
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
servaddr.sin_addr.s_addr = inet_addr(IP_ADDR);
// Client info
localAddr.sin_family = AF_INET;
localAddr.sin_port = htons(PORT);
localAddr.sin_addr.s_addr = INADDR_ANY;
if ( bind(udpSocket,(const struct sockaddr *)&localAddr, sizeof(localAddr)) < 0 )
{
printf("Failed to bind\n");
return -1;
}
sendto(udpSocket, (const char *)hello, strlen(hello), 0, (const struct sockaddr *) &servaddr, sizeof(servaddr));
printf("Hello message sent.\n");
n = recvfrom(udpSocket, (char *)buffer, BUF_SIZE, 0, (struct sockaddr *) &servaddr, &len);
buffer[n] = '\0';
printf("Server : %s\n", buffer);
fflush(stdout);
closesocket(udpSocket);
WSACleanup();
while(1);
return 0;
}

Resources