[Howto] IPv4 TCP communication in C (minimal example)

posted in: computer | 0

the server-program sends the string “TestTestTest”.

the client-programm receives the string and prints it on terminal.

 

server-program:

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

int main(int argc, char *argv[])
{

 int listenfd = 0;
 int connfd = 0;
 char sendBuff[1025];
 struct sockaddr_in serv_addr;

 listenfd = socket(AF_INET, SOCK_STREAM, 0);

 serv_addr.sin_family = AF_INET;
 serv_addr.sin_port = htons(5000);
 serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);

 bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

 listen(listenfd, 10);

 while(1)
 {
   connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);

   snprintf(sendBuff, sizeof(sendBuff), "TestTestTest");
   write(connfd, sendBuff, strlen(sendBuff));

   close(connfd);
   sleep(1);
 }

}

 

client-program:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>


int main(int argc, char *argv[])
{
 int sockfd = 0;
 char recvBuff[1024];
 char serverIP[16] = "192.168.0.10";
 struct sockaddr_in serv_addr;

 memset(recvBuff, '0', sizeof(recvBuff)); 
 memset(&serv_addr, '0', sizeof(serv_addr));

 serv_addr.sin_family = AF_INET;
 serv_addr.sin_port = htons(5000);

 sockfd = socket(AF_INET, SOCK_STREAM, 0);

 inet_pton(AF_INET, serverIP, &serv_addr.sin_addr);

 connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));

 read(sockfd, recvBuff, sizeof(recvBuff)-1);
 fputs(recvBuff, stdout);

return 0;
}