TCP网络程序设计

 

tcp_server.c

#include<stdio.h>
#include<sys/socket.h>
#include<string.h>
#include<netinet/in.h>
#define portnum 3333

int main()
{
struct sockaddr_in server_addr;
struct sockaddr_in client_addr;
char buffer[128];
int nbyte;
int sockfd,new_fd,sin_size;
//1创建套接字
  if( (sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("creat socket failed\n");
exit(1);
}

//2.1设置地址
bzero(&server_addr,sizeof(struct sockaddr_in));
server_addr.sin_family=AF_INET;
server_addr.sin_port=htos(portnum);
server_addr.sin_addr.s_addr=htonl(INADDR_ANY);


//2绑定地址
bind(sockfd, (struct sockaddr *)(&server_addr),sizeof(struct sockaddr));

//3监听端口
listen(sockfd,5);
while(1)
{
//4等待连接
sin_size=sizeof(struct sockaddr)
new_fd=accept(sockfd,(struct sockaddr *)(&client_addr), &sin_size);
printf("server get connection from %s\n",inet_ntoa(client_addr.sin_addr));

//5接收数据
nbyte=recv(new_fd,buffer,128,0);
buffer[nbyte]='\0';
printf("server received: %s\n",buffer);
//6结束连接
close(new_fd);
}
close(sockfd);
return 0;
}

 

tcp_client.c

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

#define portnum 3333

int main()
{
char buffer[128];
struct sockaddr_in server_addr;
int sockfd;

//1连接套接字
  if( (sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("creat socket failed\n");
exit(1);
}

//2.1设置要连接的服务器地址
bzero(&server_addr,sizeof(struct sockaddr_in));
server_addr.sin_family=AF_INET;
server_addr.sin_port=htos(portnum);
server_addr.sin_addr.s_addr=inet_addr("192.168.124.129"); //in_addr_t inet_addr(const char *cp)功能:将字符串形式的IP地址转化为整数型的IP地址(网络字节序)

//2.2连接服务器
if( connect(sockfd, (struct sockaddr *)(&server_addr),sizeof(struct sockaddr))==-1)
{
printf("connect socket failed\n");
exit(1);
}


//3发送数据到服务器
printf("please input char:\n");
fgets(buffer,128,stdin);
send(sockfd,buffer,strlen(buffer),0);

//4关闭连接
close(sockfd);
return 0;

}

posted @ 2017-08-17 20:41  聊哥  阅读(136)  评论(0编辑  收藏  举报