该程序是一个虽然简单但是完整的tcp客户端/服务端实例。实现了本机客户与本机服务器的连接建立及相互发送消息。建立连接之后,客户端接收并打印出服务器发送来的数据。服务器打印出客户端的IP地址并向客户端发送数据。
服务器程序srv.c如下:
#include<stdio.h>
#include<strings.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#define PORT 1234
#define BACKLOG 1
int main()
{
int listenfd,connectfd;
struct sockaddr_in server;
struct sockaddr_in client;
int sin_size;
if((listenfd=(socket(AF_INET,SOCK_STREAM,0)))==-1)
{
//handle exception
perror("Creating socket failed");
exit(1);
}
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
server.sin_addr.s_addr=htonl(INADDR_ANY);
/*Bind socket to address*/
if(bind(listenfd,(struct sockaddr *)&server,sizeof(struct sockaddr))==-1)
{
perror("Bind error");
exit(1);
}
/*Listen client's reqirement*/
if(listen(listenfd,BACKLOG)==-1)
{
perror("listen failed");
exit(1);
}
sin_size=sizeof(struct sockaddr_in);
if((connectfd=accept(listenfd,(struct sockaddr *)&client,&sin_size))==-1)
{
perror("accept() error");
exit(1);
}
//prints client's IP
printf("You got a connection from %s\n",inet_ntoa(client.sin_addr));
send(connectfd,"Welcome to my server.\n",22,0);
close(connectfd);
close(listenfd);
}
客户端程序cli.c如下:
#include<stdio.h>
#include<unistd.h>
#include<strings.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#define PORT 1234
#define MAXDATASIZE 100
int main(int argc,char *argv[])
{
int fd,numbytes;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in server;
if(argc!=2)
{
printf("Usage:%s<IP Address>",argv[0]);
exit(1);
}
if((he=gethostbyname(argv[1]))==NULL)
{
perror("gethostbyname() error\n");
exit(1);
}
if((fd=(socket(AF_INET,SOCK_STREAM,0)))==-1)
{
printf("socket() error");
exit(1);
}
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(PORT);
server.sin_addr=*((struct in_addr*)he->h_addr);
/*Connect to server and receive data from the server.*/
if(connect(fd,(struct sockaddr *)&server,sizeof(struct sockaddr))==-1)
{
printf("connect() error\n");
exit(1);
}
if((numbytes=recv(fd,buf,MAXDATASIZE,0))==-1)
{
printf("recv() error");
exit(1);
}
buf[numbytes]='\0';
printf("Server Message: %s\n",buf);
close(fd);
}
编译之后,首先启动服务器程序:
[root@mylinux 20160910]# ./srv
再启动客户端程序:
[root@mylinux 20160910]# ./cli 127.0.0.1
服务器的运行结果:
[root@mylinux 20160910]# ./srv
You got a connection from 127.0.0.1
客户端的运行结果:
[root@mylinux 20160910]# ./cli 127.0.0.1
Server Message: Welcome to my server.