UNIX网络编程(unp)源码下载和编译
UNP在linux上环境搭建
主要参考第一个链接。
在修改/usr/include/linux/socket.h这个只读文件时,需要执行命令:sudo chmod 444 socket.h
注:
sudo chmod 666 socket.h
:666是改1653为可读可写专的文件;
sudo chmod 222 socket.h
:222是改为可写,但是不可读的文件;
sudo chmod 222 socket.h
:444是改为只读文件;
参考链接1
参考链接2
解决方案参考链接:
1.https://blog.csdn.net/linda_ds/article/details/70880715
2.http://blog.chinaunix.net/uid-25795468-id-296771.html
ming@ming-Lenovo-G50-80:~/unpv13e/intro$ ./daytimetcpcli 132.163.96.1
58997 20-05-28 13:18:23 50 0 0 224.1 UTC(NIST) *
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 4094
int main(int argc, char **argv)
{
int sockfd, n;
char recvline[MAXLINE + 1];
struct sockaddr_in servaddr;
struct hostent *hptr;
char **pptr;
char str[16];
if (argc != 2) {
printf("Usage: %s \n", argv[0]);
return 1;
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("Socket error.\n");
return 2;
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(135); /* daytime server */
// servaddr.sin_addr = the IP address obtained by follows.
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <=0 ) {
if ((hptr = gethostbyname(argv[1])) == NULL) {
printf("gethostbyname error.\n");
return 3;
}
pptr = hptr->h_addr_list;
inet_ntop(AF_INET, *pptr, str, sizeof(str));
if (inet_pton(AF_INET, str, &servaddr.sin_addr) <=0) {
printf("inet_pton error.\n");
return 3;
}
}
if (connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) < 0) {
printf("connect error\n");
return 4;
}
while ( (n= read(sockfd, recvline, MAXLINE)) > 0 ) {
recvline[n] = 0;
if (fputs(recvline, stdout) == EOF) {
printf("fputs error\n");
return 5;
}
}
if ( n < 0) {
printf("read error\n");
return 6;
}
exit(0);
}
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 4094
int main(int argc, char **argv)
{
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[MAXLINE];
time_t ticks;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(135);
bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
listen(listenfd, 4);
for (;;) {
printf("waiting\n");
connfd = accept(listenfd, (struct sockaddr *)NULL, NULL);
ticks = time(NULL);
printf("in\n");
snprintf(buff, sizeof(buff), "hello %.24s\r\n", ctime(&ticks));
write(connfd, buff, strlen(buff));
close(connfd);
}
}
step1:生成daytime.c文件,并使用gcc daytime.c -o daytime
进行编译,生成可执行文件daytime
step2:生成daytimed.c文件,并使用gcc daytimed.c -o daytimed
进行编译,生成可执行文件daytimed
step3:由于没有两台机器因此在一台电脑开两个终端进行操作,首先查看本机ip地址(本机既做客户机又做服务器),运行下列程序:
sudo apt install net-tools
ifconfig -a
在wlp3s0
中的inet一栏中显示自己的ip地址
step4:开两个终端:
服务器端运行sudo ./daytimed
客户机端运行./daytimec 192.168.0.101
测试结果:
hello Thu May 28 22:07:16 2020