1、安裝 xinetd
sudo apt-get install xinetd
2、修改配置文件
cd /etc/xinetd.d
sudo vim daytime
3、重新載入 xinetd
sudo invoke-rc.d xinetd reload
4、測試
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#define BUFFER_SIZE 1024
int main(int argc, char* argv[]) {
assert(argc == 2);
char* hostname = argv[1];
// 通過主機名獲取主機信息
struct hostent* hostinfo = gethostbyname(hostname);
assert(hostinfo);
// 通過服務名獲取主機信息
struct servent* servinfo = getservbyname("daytime", "tcp");
assert(servinfo);
printf("the daytime port is %d\n", ntohs(servinfo->s_port));
// 設置地址信息
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_port = servinfo->s_port;
address.sin_addr = *(struct in_addr*)* hostinfo->h_addr_list;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
int result = connect(sockfd, (struct sockaddr*)&address, sizeof(address));
if (result == -1) {
printf("error: %d, msg: %s\n", errno, strerror(errno));
return 1;
}
char buffer[BUFFER_SIZE];
result = read(sockfd, buffer, sizeof(buffer));
assert(result > 0);
buffer[result] = '\0';
printf("the day time is: %s\n", buffer);
close(sockfd);
return 0;
}