网络编程之getsockname、getpeername、gethostbyname函数

网络编程之getsockname、getpeername、gethostbyname函数


getsockname()、getpeername()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#define ERR_EXIT(m) \
do { \
perror(m); \
exit(EXIT_FAILURE); \
} while(0) \
struct packet {
int len;
char buf[1024];
};
int main() {
int sockfd;
if ((sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
ERR_EXIT("socket");
}
struct sockaddr_in serveraddr;
memset(&serveraddr, 0, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(5534);
serveraddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(sockfd, (struct sockaddr*)&serveraddr, sizeof(serveraddr)) < 0) {
ERR_EXIT("connect");
}
struct sockaddr_in addr;
int len = sizeof(addr);
if (getsockname(sockfd, (struct sockaddr*)&addr, &len) < 0) {
ERR_EXIT("getsockname");
}
printf("ip=%s, port=%d\n", inet_ntoa(addr.sin_addr), ntohs(addr.sin_port));
struct sockaddr_in peeraddr;
int peerlen = sizeof(peeraddr);
if (getpeername(sockfd, (struct sockaddr*)&peeraddr, &peerlen) < 0) {
ERR_EXIT("getsockname");
}
printf("ip=%s, port=%d\n", inet_ntoa(peeraddr.sin_addr), ntohs(peeraddr.sin_port));
struct packet send_packet;
struct packet recv_packet;
while (fgets(send_packet.buf, sizeof(send_packet.buf), stdin) != 0) {
int n = strlen(send_packet.buf);
send_packet.len = htonl(n);
write(sockfd, &send_packet, 4+n);
int ret;
if ((ret = read(sockfd, &recv_packet, 4+n)) < 0) {
ERR_EXIT("readn");
} else if (ret == 0) {
printf("server close\n");
break;
}
fputs(recv_packet.buf, stdout);
memset(&send_packet, 0, sizeof(send_packet));
memset(&recv_packet, 0, sizeof(recv_packet));
}
close(sockfd);
return 0;
}

gethostbyname()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#define ERR_EXIT(m) \
do { \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
int main() {
char host[100] = {0};
if (gethostname(host, sizeof(host)) < 0) {
ERR_EXIT("gethostname");
}
struct hostent *hp;
if ((hp = gethostbyname(host)) == NULL) {
ERR_EXIT("gethostbyname");
}
int i=0;
while(hp->h_addr_list[i] != NULL) {
printf("%s\n", inet_ntoa(*(struct in_addr*)hp->h_addr_list[i]));
++i;
}
return 0;
}