socket编程热身程序

时间:2024-10-23 22:05:32
 /*server.c*/
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <unistd.h>
#define err_log(errlog) do{ perror(errlog); exit(1);}while(0)
int main(int argc, const char *argv[])
{
int sockfd;
int acceptfd;
struct sockaddr_in serveraddr, clientaddr;

16 if (argc != 3)
{
fprintf(stderr,"Usage:%s serverip port.\n", argv[]);
return -;
}
/*server端 第一步:socket 创建套接字*/
if((sockfd = socket(AF_INET, SOCK_STREAM, )) < )
{
err_log("fail to socket");
}
/*server端 第二步: 填充网络信息结构体*/
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = inet_addr(argv[]);//argv[1]:由手动输入,终端的第二个参数
serveraddr.sin_port = htons(atoi(argv[]));//htons 将本地字节序变为网络字节序,atoi将数字类字符串转化为数字,如字符串“80” 变为数字80
/*server端 第三步 :bind() 绑定*/
if(bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < )
{
err_log("fail to bind");
}
/*server端 第四步:listen() 监听*/
if(listen(sockfd, ) < )
{
err_log("fail to listen");
} socklen_t addrlen = sizeof(struct sockaddr_in);
/*接收客户端的连接请求*/
acceptfd = accept(sockfd, (struct sockaddr *)&clientaddr, &addrlen); if(acceptfd < )
{
err_log("fail to acceptfd");
} printf("%s --> %d\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port));
/*inet_ntoa函数将网络字节序的IP地址转换为十进制的字符串*/
/*ntohs 将网络端口号转换为本地端口号*/
close(acceptfd); //关闭文件描述符
close(sockfd);//关闭文件描述符 52 return ;
}

 /*client*/
#include <stdio.h>
#include <arpa/inet.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <unistd.h>
#define err_log(errlog) do{ perror(errlog); exit(1);}while(0) int main(int argc, const char *argv[])
{
int sockfd;
int acceptfd;
struct sockaddr_in serveraddr, clientaddr; if(argc != )
{
fprintf(stderr,"Usage:%s serverip port.\n", argv[]);
return -;
}
/*client端 第一步:socket套接字*/
if((sockfd = socket(AF_INET, SOCK_STREAM, )) < )
{
err_log("fail to socket");
}
/*client端 第二部:填充网络信息结构体*/
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = inet_addr(argv[]);
serveraddr.sin_port = htons(atoi(argv[]));
/*client端 第三步:连接服务器端*/
if(connect(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) < )
{
err_log("fail to connect");
}
close(sockfd);//关闭文件描述符
return ;
}

相关文章