下面由linux系统教程栏目给大家介绍LINUX中的socket与VRF,希望对需要的朋友有所帮助!
LINUX socket与VRF
实验环境如下图所示:
配置如下:
#!/bin/bash sudo ip netns add ns1 sudo ip link add ns1veth1 type veth peer name eth0 netns ns1 sudo ip netns add ns2 sudo ip link add ns2veth1 type veth peer name eth0 netns ns2 sudo ip link set ns1veth1 master vrftest sudo ip link set ns2veth1 master vrftest sudo ip link set ns2veth1 up sudo ip link set ns1veth1 up sudo ip addr add 1.1.1.254/24 dev ns1veth1 sudo ip addr add 2.2.2.254/24 dev ns2veth1 sudo ip netns exec ns2 ip addr add 2.2.2.1/24 dev eth0 sudo ip netns exec ns1 ip addr add 1.1.1.1/24 dev eth0 sudo ip netns exec ns1 ip link set eth0 up sudo ip netns exec ns1 ip link set lo up sudo ip netns exec ns1 ip route add default via 1.1.1.254 dev eth0 sudo ip netns exec ns2 ip link set eth0 up sudo ip netns exec ns2 ip link set lo up sudo ip netns exec ns2 ip route add default via 2.2.2.254 dev eth0
实验使用c语言写了两个套接字交互程序:
- 服务器:vrfs
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<errno.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include <unistd.h> #define MAXLINE 4096 int main(int argc, char** argv) { int listenfd, connfd; struct sockaddr_in servaddr; char buff[4096]; int n; int on = 1; if( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ){ printf("create socket error: %s(errno: %d)n",strerror(errno),errno); exit(0); } setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); setsockopt(listenfd, SOL_SOCKET, SO_REUSEPORT, (void *)&on, sizeof(on)); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(6666); if(argc == 2){ printf("vrf device name: %srn", argv[1]); if(0 > setsockopt(listenfd, SOL_SOCKET, SO_BINDTODEVICE, argv[1], strlen(argv[1])+1)){ printf("bind socket master dev error: %s(errno: %d)n",strerror(errno),errno); exit(0); } } if( bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1){ printf("bind socket error: %s(errno: %d)n",strerror(errno),errno); exit(0); } if( listen(listenfd, 10) == -1){ printf("listen socket error: %s(errno: %d)n",strerror(errno),errno); exit(0); } printf("======waiting for client's request======n"); while(1){ if((connfd = accept(listenfd, (struct sockaddr*)NULL, NULL)) == -1){ printf("accept socket error: %s(errno: %d)",strerror(errno),errno); continue; } n = recv(connfd, buff, MAXLINE, 0); buff[n] = '