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
| #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#define BUF_LEN 2048
#define PORT 8080
int main(int argc, char *argv[])
{
int sock = -1;
socklen_t addr_len = 0;
struct sockaddr_in6 serv_addr = {0};
char buf[BUF_LEN] = {0};
int err = -1;
/* 建立socket */
sock = socket(AF_INET6, SOCK_STREAM, 0);
if (-1 == sock) {
perror("socket error: ");
return -1;
}
memset(&serv_addr, 0x0, sizeof(serv_addr));
/* 填充地址结构 */
serv_addr.sin6_family = AF_INET6;
serv_addr.sin6_port = htons(PORT);
//serv_addr.sin6_addr = in6addr_loopback; /* 连接到环回地址 */
//inet_pton(AF_INET6, "2002:da80:e000::1:1:9", &serv_addr.sin6_addr);
//inet_pton(AF_INET6, "::ffff:c0a8:0208", &serv_addr.sin6_addr);
//inet_pton(AF_INET6, "::c0a8:0205", &serv_addr.sin6_addr);
// connect到链路本地地址,需要设置sin6_scope_id,用`ip addr show`获取
serv_addr.sin6_scope_id = 2;
inet_pton(AF_INET6, "fe80::a00:27ff:fea0:67d6", &serv_addr.sin6_addr);
addr_len = sizeof(serv_addr);
err = connect(sock, (struct sockaddr *)&serv_addr, addr_len);
if (-1 == err) {
perror("connect error:");
close(sock);
return -1;
}
/* 发送消息 */
memset(buf, 0x0, BUF_LEN);
snprintf(buf, BUF_LEN - 1, "hello server, I'm client\n");
err = send(sock, buf, strlen(buf), 0);
if (err < 0) {
perror("send error:");
close(sock);
return -1;
}
/* 接收消息 */
memset(buf, 0x0, BUF_LEN);
err = recv(sock, buf, BUF_LEN, 0);
if (err < 0) {
perror("recv error:");
close(sock);
return -1;
}
printf("recv %d bytes: %s\n", err, buf);
close(sock);
return 0;
}
|