之前学习的时候笔记没有保存好,这次重新编写一个案例。
客户端实现程序代码:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h> #define DEF_TCP_SRV_PORT 19868 int main()
{ struct sockaddr_in addr;
struct sockaddr_in srv_addr;
int net_sock;
int new_fd; int res;
int len; char buff[]; // 1. socket 初始化
// 1.1 创建socket
net_sock = socket(AF_INET,SOCK_STREAM,);
if( - == net_sock )
{
printf("create socket error!\r\n");
return -;
}
// 1.2 初始化地址
bzero( &addr, sizeof(struct sockaddr_in)); addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_family = AF_INET;
addr.sin_port = htons(DEF_TCP_SRV_PORT); // 1.3 bind地址
bind( net_sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)); //监听
listen( net_sock, ); len = sizeof(struct sockaddr);
new_fd = accept( net_sock, (struct sockaddr *)(&srv_addr),&len ); printf("server ip:%s\r\n",inet_ntoa(srv_addr.sin_addr)); res = recv(new_fd, buff,,);
buff[res] ='\0'; printf("get : %s\r\n",buff); close(net_sock); return ;
};
服务端程序代码:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h> #define DEF_TCP_SRV_PORT 19868 int main()
{
struct sockaddr_in srv_addr;
int sock;
int res;
char buff[]; //创建套接字
sock = socket(AF_INET,SOCK_STREAM,); if( - == sock )
{
printf("create sock failed\r\n");
return -;
} //设置要绑定的地址
bzero( &srv_addr, sizeof(struct sockaddr_in)); srv_addr.sin_addr.s_addr = inet_addr("192.168.1.21");
srv_addr.sin_family = AF_INET;
srv_addr.sin_port = htons(DEF_TCP_SRV_PORT); //连接
res = connect(sock,(struct sockaddr *)(&srv_addr),sizeof(struct sockaddr)); if( -==res)
{
printf("connect failed\r\n");
return -;
} printf("please input data:\r\n");
fgets(buff,,stdin);
//发送数据
send( sock, buff, strlen(buff),); close(sock); }