This is a very simple and buggy TCP socket example in Linux C. For demo only.
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int server_sockfd; // Server socket
int client_sockfd; // Client socket
int len;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
int sin_size;
char buf[BUFSIZ]; // data buf
memset(&my_addr,0,sizeof(my_addr)); // initialize
my_addr.sin_family=AF_INET;
my_addr.sin_addr.s_addr=htonl(INADDR_ANY); // In addr, what server addresses are allowed.
my_addr.sin_port=htons(8000); // Server's port
// Create a socket
if((server_sockfd=socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
return 1;
}
// Bind socket to interfaces.
if (bind(server_sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0)
{
perror("bind");
return 1;
}
// Listen, and set backlog to 5.
listen(server_sockfd,5);
sin_size=sizeof(struct sockaddr_in);
// Accept incoming connections.
if((client_sockfd=accept(server_sockfd,(struct sockaddr *)&remote_addr,&sin_size))<0)
{
perror("accept");
return 1;
}
printf("accept client %s/n",inet_ntoa(remote_addr.sin_addr));
len=send(client_sockfd,"Welcome to my server/n",21,0);
// Receive data from client, and send it back.
while((len=recv(client_sockfd,buf,BUFSIZ,0))>0)
{
buf[len]='/0';
printf("%s/n",buf);
if(send(client_sockfd,buf,len,0)<0)
{
perror("write");
return 1;
}
}
close(client_sockfd);
close(server_sockfd);
return 0;
}
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
int server_sockfd; // Server socket
int client_sockfd; // Client socket
int len;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
int sin_size;
char buf[BUFSIZ]; // data buf
memset(&my_addr,0,sizeof(my_addr)); // initialize
my_addr.sin_family=AF_INET;
my_addr.sin_addr.s_addr=htonl(INADDR_ANY); // In addr, what server addresses are allowed.
my_addr.sin_port=htons(8000); // Server's port
// Create a socket
if((server_sockfd=socket(PF_INET,SOCK_STREAM,0))<0)
{
perror("socket");
return 1;
}
// Bind socket to interfaces.
if (bind(server_sockfd,(struct sockaddr *)&my_addr,sizeof(struct sockaddr))<0)
{
perror("bind");
return 1;
}
// Listen, and set backlog to 5.
listen(server_sockfd,5);
sin_size=sizeof(struct sockaddr_in);
// Accept incoming connections.
if((client_sockfd=accept(server_sockfd,(struct sockaddr *)&remote_addr,&sin_size))<0)
{
perror("accept");
return 1;
}
printf("accept client %s/n",inet_ntoa(remote_addr.sin_addr));
len=send(client_sockfd,"Welcome to my server/n",21,0);
// Receive data from client, and send it back.
while((len=recv(client_sockfd,buf,BUFSIZ,0))>0)
{
buf[len]='/0';
printf("%s/n",buf);
if(send(client_sockfd,buf,len,0)<0)
{
perror("write");
return 1;
}
}
close(client_sockfd);
close(server_sockfd);
return 0;
}