views:

51

answers:

3

I am working on Ubuntu 9.04. I am running this on VMware workstation. Here is my C code:

int sockfd,cnt,addrlen;
const int on = 1;
struct sockaddr_in servaddr,cliaddr;
char reply[512];

sockfd = socket(AF_INET, SOCK_DGRAM, 0);

if (sockfd < 0) {
   perror("socket");
   exit(1);
}

setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR, &on,sizeof(on));
bzero(&cliaddr, sizeof(cliaddr));
cliaddr.sin_family = AF_INET;
cliaddr.sin_addr.s_addr = htonl(INADDR_ANY);
cliaddr.sin_port = htons(68);
addrlen = sizeof(servaddr);

if (bind(sockfd, (struct sockaddr *) &cliaddr, sizeof(cliaddr)) < 0) {        
  perror("bind");
  exit(1);
} 

while(1)
{       
   cnt = recvfrom(sockfd, reply, sizeof(reply), 0,(struct sockaddr *) &servaddr, &addrlen);

   if (cnt < 0) {
     perror("recvfrom");
     exit(1);
   } 

   printf("\nReply Received\n");
}

I run this program in one terminal and run 'dhclient' on another. I receive no datagrams. What am I doing wrong?

A: 

I recommend this tutorial. Also, are you running as root? You can't get that low-numbered port otherwise.

bmargulies
Yes I am running as root
Ryan
+1  A: 

I'm not sure what you're doing wrong but if I were you I'd write my own client which is very simple and see if it can talk to your server code above (who knows what dhclient might do outside of contact your code). I'd also temporarily change the port number to something not well-known. This way I wouldn't be interfering with any other programs and interfaces.

shank
+1  A: 

Looks like you're listening on UDP port 68 for a broadcasted message from the client? If I'm reading DHCP correctly, the client will send its broadcase 'discover' request FROM UDP port 68, but TO UDP port 67 on the server, so you would need to be listening on port 67 to receive it.

An easy 'first' test to test you're code before trying it with dhclient would be to try talking to your server with netcat. a command line like

echo "Foo" | netcat -u localhost 68

Should cause a packet to be received by your current code.

Another good debugging tool is wireshark which will let you see exactly what UDP packets are being sent by dhclient and what they contain.

bdk