标签:
现在可以改进客户程序,使它可以连接到任何有名字的主机,这次不是连接到示例服务器,而是连接到一个标准服务,这样就可以演示端口号的提取操作了./*************************************************************************
> File Name: getdate.c
> Description: getdate.c
> Author: Liubingbing
> Created Time: 2015年07月24日 星期五 20时26分04秒
> Other: getdate.c
************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
int main(int argc, char *argv[])
{
char *host;
int sockfd;
int len, result;
struct sockaddr_in address;
struct hostent *hostinfo;
struct servent *servinfo;
char buffer[128];
if (argc == 1)
host = "localhost";
else
host = argv[1];
/* 查找主机的地址,如果找不到,就报告一条错误 */
hostinfo = gethostbyname(host);
if (!hostinfo) {
fprintf(stderr, "no host: %s\n", host);
exit(1);
}
/* 检查主机上是否有daytime服务 */
servinfo = getservbyname("daytime", "tcp");
if (!servinfo) {
fprintf(stderr, "no daytime service\n");
exit(1);
}
printf("daytime port is %d\n", ntohs(servinfo->s_port));
/* 创建一个套接字 */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
/* 构造connect调用要使用的地址 */
address.sin_family = AF_INET;
address.sin_port = servinfo->s_port;
address.sin_addr = *(struct in_addr *)*hostinfo->h_addr_list;
len = sizeof(address);
/* 然后建立连接并取得有关信息 */
result = connect(sockfd, (struct sockaddr *)&address, len);
if (result == -1) {
perror("oops: getdate");
exit(1);
}
result = read(sockfd, buffer, sizeof(buffer));
buffer[result] = '\0';
printf("read %d bytes: %s", result, buffer);
close(sockfd);
exit(0);
}可以用getdate获取任一已知主机的日期和时间.#include <sys/socket.h> int setsockopt(int socket, int level, int option_name, const void *option_value, size_t option_len);可以在协议层次的不同级别对选项进行设置.如果想要在套接字级别设置选项,就必须将level参数设置为SOL_SOCKET.
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/yiranant/article/details/47049103