搭建《UNIX网络编程》那本书所需的环境
1.ubuntu18系统安装编译器,build-essential
sudo apt-get install build-essential
2.下载书中的头文件以及实例源码:http://www.unpbook.com/src.html
3.解压下载的unpv13e.tar.gz 进行一波骚气操作
tar -xzvf unpv13e.tar.gz
chmod u+x configure
./configure
cd lib
make
cd ../libfree # continue building the basic library
make
cd ../libgai # the getaddrinfo() and getnameinfo() functions
make
当出现如下错误
gcc -I../lib -g -O2 -D_REENTRANT -Wall -c -o inet_ntop.o inet_ntop.c
inet_ntop.c: In function ‘inet_ntop’:
inet_ntop.c:60:9: error: argument ‘size’ doesn’t match prototype
size_t size;
^~~~
In file included from inet_ntop.c:27:0:
/usr/include/arpa/inet.h:64:20: error: prototype declaration
extern const char *inet_ntop (int __af, const void *__restrict __cp,
^~~~~~~~~
<builtin>: recipe for target 'inet_ntop.o' failed
make: *** [inet_ntop.o] Error 1
在inet_ntop.c中添加如下代码
#define size_t socklen_t
4.将生成的libunp.a静态库复制到/usr/lib/和/usr/lib64/中
cd .. //回到unpv12e目录
sudo cp libunp.a /usr/lib
sudo cp libunp.a /usr/lib64
5.修改unp.h并将其和config.h拷贝到/usr/include中,为了以后include方便
gedit lib/unp.h //将unp.h中#include "../config.h"修改为#include "config.h"
sudo cp lib/unp.h /usr/include
sudo cp config.h /usr/include
6.编译源代码
cd ./intro
gcc daytimetcpcli.c -o daytimetcpcli -lunp
7.编写程序
#include "unp.h"
int main(int argc,char ** argv)
{
int sockfd,n;
char recvline[MAXLINE + 1];
struct sockaddr_in servaddr;
if(argc != 2)
err_quit("usage: a.out <IPaddress>");
if((sockfd = socket(AF_INET,SOCK_STREAM,0)) < 0 )
err_sys("socket error");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13);
if(inet_pton(AF_INET, argv[1],&servaddr.sin_addr) <= 0)
err_quit("inet_pton error for %s",argv[1]);
if(connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)
err_sys("connect error");
while((n = read(sockfd,recvline,MAXLINE)) > 0 )
{
recvline[n] = 0;
if(fputs(recvline,stdout) == EOF)
err_sys("fputs error");
}
if(n < 0)
err_sys("read error");
exit(0);
}
兴致勃勃的打开命令符窗口来了一波操作
Connection refused!!!
经过一番查找,发现是因为daytime服务没有开启 来一波安装命令(sudo apt-get install xinetd)
然后 vi /etc/xinetd.d/daytim 再将文件中的 disable yes 改为 disable no
重启xinetd服务 service xinetd restart 这时候再来一波实例操作、
完美获取成功。
总结:虽然一开始有点蒙,但还是算是完成了第一个编写的小实例。