Hi All:
I am confused by the bind useage.
My OS is linux redhat 7.1 with kernel 2.2.
When I make a program to received a broadcast message (255.255.255.255).
If I bind the address with INADDR_ANY, I can receive the broadcast
message.
But if I bind with ipaddess with my netcard with the ip 192.168.0.33, then I
can
not receive any more.
Below is the source code, please give me some advices.
Thank you and best regards!
Leo
#include <stdio.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#define SERV_UDP_PORT 3233
char recvbuffer[1024];
int main()
{
int sockfd;
struct sockaddr_in serv_addr, cli_addr;
int localip, on;
unsigned int socklen;
/*
* Open a UDP socket (an Internet datagram socket).
*/
if ( (sockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
printf("server: can't open datagram socket");
return -1;
}
/*
* Bind our local address so that the client can send to us.
*/
localip = inet_addr("192.168.0.33");
printf("local ip address %d\n", localip);
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
#if 0
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
#else
serv_addr.sin_addr.s_addr = localip;
#endif
serv_addr.sin_port = htons(SERV_UDP_PORT);
printf("local ip port %d\n", serv_addr.sin_port);
on = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof (on)) < 0)
{
printf("setsockopt of SO_REUSEADDR error");
}
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
{
printf("server: can't bind local address");
}
socklen = sizeof(struct sockaddr_in);
if (getsockname(sockfd, (struct sockaddr *) &cli_addr, &socklen) < 0)
{
printf("getsockname() error\n");
}
printf("bind address is [%ld] port is [%d]\n", cli_addr.sin_addr.s_addr,
cli_addr.sin_port);
for (;;)
{
int n;
socklen = sizeof(struct sockaddr_in);
n = recvfrom(sockfd, recvbuffer, 1024, 0, (struct sockaddr
*)&cli_addr, &socklen);
if (n < 0)
{
printf("recvfrom error\n");
continue;
}
recvbuffer[n] = '\0';
printf("received message: %s\n", recvbuffer);
}
return 0;
}
|