网络编程的几个结构体
时间:2011-02-23 来源:macula7
示例:
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <netdb.h>
int main(int argc, char *argv[])
{
struct hostent *host;
if(argc != 2)
{
printf("usage: getip address\n");
exit(-1);
}
if((host = gethostbyname(argv[1])) == NULL)
{
herror("gethostbyname error");
exit(1);
}
printf("Host name:%s\n", host->h_name);
printf("IP Address:%s\n", inet_ntoa(*((struct in_addr *)host->h_addr)));
return 0;
}
protoent结构体struct protoent {
char * p_name; //名称
char * p_aliases; //别名
4 short * p_proto; //编号
5 }
示例:
#include <netdb.h>
main()
{
int number;
struct protoent *protocol;
for(number=0; number<5; number++)
{
protocol = getprotobynumber(number);
if(protocol == (struct protoent * ) NULL) continue;
printf("%2d: %-10s: %-10s\n", protocol->p_proto, protocol->p_name, protocol->p_aliases[0]);
}
}
结构体 in_addr sockaddr_instruct in_addr{
In_addr_t s_addr; //32bit的地址
}
struct sockaddr_in
{
unit8_t sin_len; //
sa_family sin_family; //AF_INET
in_port_t sin_port; //16bit
struct in_addr sin_addr;//32bit
char sin_zero[8];
}
inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
这里的servaddr是sockaddr_in类型,servaddr.sin_addr是in_addr类型
相关阅读 更多 +