Programming UDP sockets in C on Linux – Client and Server example
This article describes how to write a simple echo server and client using udp sockets in C on Linux/Unix platform.
UDP sockets or Datagram sockets are different from the TCP sockets in a number of ways.
The most important difference is that UDP sockets are not connection oriented. More technically speaking, a UDP server does not accept connections and a udp client does not connect to server.
The server will bind and then directly receive data and the client shall directly send the data.
Simple UDP Server
So lets first make a very simple ECHO server with UDP socket. The flow of the code would be
socket() -> bind() -> recvfrom() -> sendto()
/* Simple udp server */ #include //printf #include //memset #include //exit(0); #include #include #define BUFLEN 512 //Max length of buffer #define PORT 8888 //The port on which to listen for incoming data void die(char *s) < perror(s); exit(1); >int main(void) < struct sockaddr_in si_me, si_other; int s, i, slen = sizeof(si_other) , recv_len; char buf[BUFLEN]; //create a UDP socket if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) < die("socket"); >// zero out the structure memset((char *) &si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(PORT); si_me.sin_addr.s_addr = htonl(INADDR_ANY); //bind socket to port if( bind(s , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1) < die("bind"); >//keep listening for data while(1) < printf("Waiting for data. "); fflush(stdout); //try to receive some data, this is a blocking call if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == -1) < die("recvfrom()"); >//print details of the client/peer and the data received printf("Received packet from %s:%d\n", inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port)); printf("Data: %s\n" , buf); //now reply the client with the same data if (sendto(s, buf, recv_len, 0, (struct sockaddr*) &si_other, slen) == -1) < die("sendto()"); >> close(s); return 0; >
Run the above code by doing a gcc server.c && ./a.out at the terminal. Then it will show waiting for data like this
$ gcc server.c && ./a.out Waiting for data.
Next step would be to connect to this server using a client. We shall be making a client program a little later but first for testing this code we can use netcat.
Test the server with netcat
Open another terminal and connect to this udp server using netcat and then send some data. The same data will be send back by the server. Over here we are using the ncat command from the nmap package.
$ ncat -vv localhost 8888 -u Ncat: Version 5.21 ( http://nmap.org/ncat ) Ncat: Connected to 127.0.0.1:8888. hello hello world world
Note : We had to use netcat because the ordinary telnet command does not support udp protocol. The -u option of netcat specifies udp protocol.
Check open port with netstat
The netstat command can be used to check if the udp port is open or not.
$ netstat -u -a Active Internet connections (servers and established) Proto Recv-Q Send-Q Local Address Foreign Address State udp 0 0 localhost:11211 *:* udp 0 0 localhost:domain *:* udp 0 0 localhost:45286 localhost:8888 ESTABLISHED udp 0 0 *:33320 *:* udp 0 0 *:ipp *:* udp 0 0 *:8888 *:* udp 0 0 *:17500 *:* udp 0 0 *:mdns *:* udp 0 0 localhost:54747 localhost:54747 ESTABLISHED udp6 0 0 [::]:60439 [::]:* udp6 0 0 [::]:mdns [::]:*
Note the *:8888 entry of output. Thats our server program.
The entry that has localhost:8888 in «Foreign Address» column, indicates some client connected to it, which is netcat over here.
UDP Client
Now that we have tested our server with netcat, its time to make a client and use it instead of netcat.
The program flow is like
/* Simple udp client */ #include //printf #include //memset #include //exit(0); #include #include #define SERVER "127.0.0.1" #define BUFLEN 512 //Max length of buffer #define PORT 8888 //The port on which to send data void die(char *s) < perror(s); exit(1); >int main(void) < struct sockaddr_in si_other; int s, i, slen=sizeof(si_other); char buf[BUFLEN]; char message[BUFLEN]; if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) < die("socket"); >memset((char *) &si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; si_other.sin_port = htons(PORT); if (inet_aton(SERVER , &si_other.sin_addr) == 0) < fprintf(stderr, "inet_aton() failed\n"); exit(1); >while(1) < printf("Enter message : "); gets(message); //send the message if (sendto(s, message, strlen(message) , 0 , (struct sockaddr *) &si_other, slen)==-1) < die("sendto()"); >//receive a reply and print it //clear the buffer by filling null, it might have previously received data memset(buf,'/* Simple udp client */ #include //printf #include //memset #include //exit(0); #include #include #define SERVER "127.0.0.1" #define BUFLEN 512 //Max length of buffer #define PORT 8888 //The port on which to send data void die(char *s) < perror(s); exit(1); >int main(void) < struct sockaddr_in si_other; int s, i, slen=sizeof(si_other); char buf[BUFLEN]; char message[BUFLEN]; if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) < die("socket"); >memset((char *) &si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; si_other.sin_port = htons(PORT); if (inet_aton(SERVER , &si_other.sin_addr) == 0) < fprintf(stderr, "inet_aton() failed\n"); exit(1); >while(1) < printf("Enter message : "); gets(message); //send the message if (sendto(s, message, strlen(message) , 0 , (struct sockaddr *) &si_other, slen)==-1) < die("sendto()"); >//receive a reply and print it //clear the buffer by filling null, it might have previously received data memset(buf,'\0', BUFLEN); //try to receive some data, this is a blocking call if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1) < die("recvfrom()"); >puts(buf); > close(s); return 0; >', BUFLEN); //try to receive some data, this is a blocking call if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1) < die("recvfrom()"); >puts(buf); > close(s); return 0; >
Run the above program and it will ask for some message
$ gcc client.c -o client && ./client Enter message : happy happyWhatever message the client sends to server, the same comes back as it is and is echoed.
Conclusion
UDP sockets are used by protocols like DNS etc. The main idea behind using UDP is to transfer small amounts of data and where reliability is not a very important issue. UDP is also used in broadcasting/multicasting.
When a file transfer is being done or large amount of data is being transferred in parts the transfer has to be much more reliable for the task to complete. Then the TCP sockets are used.
A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected] .
16 Comments
- Joe June 7, 2021 at 3:03 pm Hello. You seem to have double pasted the second code sample inside itself. THanks for the tutorial
- Silver Moon Post author August 14, 2018 at 4:04 pm i haven’t done sockets for a long time. right now i can think of using multiple threads do things in parallel.
so the main thread could do its background work, and an extra thread could listen to the udp port for incoming messages.
or the other way round.
but i am not sure if that is the best approach. there might be better alternatives.
- Bryan Kelly March 15, 2018 at 4:04 am And ncat used option -vv which on my Ubuntu system means verbose. The captured text does not have the verbose output. My system had five lines of information for each line of typed in data.
Still, I am new to Linux and Ubuntu and this is an unexpected cool way to test the server app.
Thank you.Клиент-сервер под linux на c++ общение клиентов «все со всеми» с использованием потоков
Начну с того, что была предложена работа на должность программиста с\с++. Задание это название темы.
Полез в интернет, кругом все напичкано чатами и общением по типу клиент-сервер, но увы кода с подобным заданием я так и не нашел. Был примитив типа ЭХО клиент-сервера, который я и решил взять за основу:
Это у нас клиент:struct sockaddr_in addr; // структура с адресом struct hostent* hostinfo; port = atoi(PORT); sock = socket(AF_INET, SOCK_STREAM, 0); // создание TCP-сокета if(sock < 0) < perror("socket"); exit(1); >// Указываем параметры сервера addr.sin_family = AF_INET; // домены Internet addr.sin_port = htons(port); // или любой другой порт. addr.sin_addr.s_addr = inet_addr("127.0.0.1"); if(connect(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) // установка соединения с серверомif( (master_socket = socket(AF_INET , SOCK_STREAM , 0)) == 0) < perror("socket failed"); exit(EXIT_FAILURE); >//set master socket to allow multiple connections , this is just a good habit, it will work without this if( setsockopt(master_socket, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt)) < 0 ) < perror("setsockopt"); exit(EXIT_FAILURE); >//type of socket created address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons( PORT ); //bind the socket to localhost port 8888 if (bind(master_socket, (struct sockaddr *)&address, sizeof(address)) <0) < perror("bind failed"); exit(EXIT_FAILURE); >printf("Listener on port %d \n", PORT); //try to specify maximum of 3 pending connections for the master socket if (listen(master_socket, 3) < 0) < perror("listen"); exit(EXIT_FAILURE); >//accept the incoming connection addrlen = sizeof(address); puts("Waiting for connections . "); while(TRUE) < if ((new_socket = accept(master_socket, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0) < perror("accept"); exit(EXIT_FAILURE); >>
После всего этого в клиенте нужно отправить сообщение серверу используя функции send или write а на стороне сервера принять сообщение и переотправить его обратно клиенту используя функции read и send.
Вообще есть разные функции отправки и приема, к примеру send и recv вместе с сообщением шлют еще и флаг подтверждения, а функции read и write не требуют подтверждения, то есть сообщение может потерять байты при отправке и это не будет зафиксировано.
Так как сокеты это дуплекс и создавая связь между клиентом и сервером мы не можем писать туда сообщения из других подключенных сокетов, необходимо создать массив со всеми активными сокетами подключенными к серверу. И еще одно замечание очень важное:
Для общения между несколькими сокетами необходимо использовать функцию select, которая выбирает сокет из списка и отсылает ему сообщение, и так далее, пока не закончатся все записанные сокеты
//clear the socket set FD_ZERO(&readfds); //add master socket to set FD_SET(master_socket, &readfds); max_sd = master_socket; //add child sockets to set for ( i = 0 ; i < max_clients ; i++) < //socket descriptor sd = client_socket[i]; //if valid socket descriptor then add to read list if(sd >0) FD_SET( sd , &readfds); //highest file descriptor number, need it for the select function if(sd > max_sd) max_sd = sd; > //wait for an activity on one of the sockets , timeout is NULL , so wait indefinitely activity = select( max_sd + 1 , &readfds , NULL , NULL , NULL); if ((activityПосле этого в массив сокетов будет записано правильное значение подключаемого сокета а далее остается лишь перебирать их при рассылке сообщений:
sd = client_socket[i]; if (FD_ISSET( sd , &readfds)) < //Check if it was for closing , and also read the incoming message if ((valread = read( sd , buffer, 1024)) == 0) < //Somebody disconnected , get his details and print getpeername(sd , (struct sockaddr*)&address , (socklen_t*)&addrlen); printf("Host disconnected , ip %s , port %d \n" , inet_ntoa(address.sin_addr) , ntohs(address.sin_port)); //Close the socket and mark as 0 in list for reuse close( sd ); user_count--; client_socket[i] = 0; >//Echo back the message that came in else < //set the string terminating NULL byte on the end of the data read buffer[valread] = '\0'; for (i = 0; i < max_clients; i++) < sd = client_socket[i]; send(sd , buffer , strlen(buffer) , 0 ); >buffer[1024] = ; > >
Запишем все это в функцию и создадим отдельный поток:
void *server(void *); pthread_create(&threadA[0], NULL, server, NULL); pthread_join(threadA[0], NULL);
Что касаемо клиента, то необходимо создать два разных потока для чтения и записи в сокет:
void *write(void *); void *read(void *); pthread_create(&threadA[0], NULL, write, NULL); pthread_create(&threadA[1], NULL, read, NULL); pthread_join(threadA[1], NULL); pthread_join(threadA[0], NULL); void *write (void *dummyPt) < for(;;) < char s[BUF_SIZE]; cout close(sock); > void *read (void *dummyPt) < char test[BUF_SIZE]; bzero(test, BUF_SIZE + 1); bool loop = false; while(!loop) < bzero(test, BUF_SIZE + 1); int rc = read(sock, test, BUF_SIZE); if ( rc >0) < string tester (test); cout > coutТеперь все работает. Спасибо за снимание. Надеюсь что это пригодится тем, кто так же как и я пытался написать клиент-сервер, но не смог найти нужную информацию в сети.