- 积分
- 3
- 鸿鹄币
- 个
- 好评度
- 点
- 精华
- 注册时间
- 2016-6-12
- 最后登录
- 1970-1-1
- 阅读权限
- 10
- 听众
- 收听
网络小学徒
![Rank: 1](https://cdn.hh010.com/static/image/common/star_level1.gif)
|
网络环境是这样的:
有三个主机A,B,C均运行linux,
A的ip是192.168.0.11
B的ip是192.168.0.12
C是双网卡,两个ip分别是192.168.0.13和10.1.1.111(该ip随便设置的)。
ABC间可以相互通信,但A,B只能通过C向外发(即10.1.1.X网段)送数据。
需实现:在C上广播,但不期望在A,B收到广播。
请问是不是可以通过在C上作简单的路由配置就可以实现以上目地,还是说在程序上作相应的改动。
C上的广播程序如下:
C/C++ code?
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
| #include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/wait.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<errno.h>
#include<fcntl.h>
#include<sys/epoll.h>
#include<pthread.h>
int main()
{
char msg[128] = "I am broadCast message from server!";
int brdcFd;
int optval = 1;//这个值一定要设置,否则可能导致sendto()失败
int sendBytes,len;
struct sockaddr_in theirAddr;
if((brdcFd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
{
printf("socket fail\n");
return -1;
}
setsockopt(brdcFd,SOL_SOCKET,SO_BROADCAST | SO_REUSEADDR,&optval,sizeof(int));
memset(&theirAddr, 0, sizeof(struct sockaddr_in));
theirAddr.sin_family = AF_INET;
theirAddr.sin_addr.s_addr = inet_addr("255.255.255.255");
theirAddr.sin_port = htons(4001);
while(1)
{
len = strlen(msg);
sendBytes = sendto(brdcFd,msg,len,0,(struct sockaddr *)&theirAddr,sizeof(struct sockaddr));
if(-1 == sendBytes)
{
printf("sendto fail, errno=%d\n", errno);
return -1;
}
printf("msg=%s, msgLen=%d, sendBytes=%d\n", msg, strlen(msg), sendBytes);
sleep(3);
}
close(brdcFd);
return 0;
}
|
谢谢各位大神!
|
|