views:

4068

answers:

4

Hi

I want to calculate the broadcast address for e.g -IP 192.168.3.1 -Subnet 255.255.255.0 =192.168.3.255

in C.

I know the way (doing fancy bitwise OR's between the inversed IP and Subnet), but my problem is I come from the green fields of MacOSX Cocoa programing. I looked into the source of ipcal, but wasn't able to integrate it into my code base. There must be a simple 10 line of code example somewhere on the internet, I just can't find it. Could someone point me to a 10 line of code example of how to do it in C.

Cheers, Kolja

+3  A: 

Just calculate

broadcast = ip | ( ~ subnet )

(Broadcast = ip-addr or the inverted subnet-mask)

The broadcast address has a "1" bit where the subnet mask has a "0" bit.

froh42
A: 

Could it be?

unsigned broadcast(unsigned ip,unsigned subnet){
    unsigned int bits = subnet ^ 0xffffffff; 
    unsigned int bcast = ip | bits;

    return bcast;
}

Edit: I considered that both ip and subnet are without "."

Tom
+1  A: 

I'm not sure if you are trying to do it in C, C# or Objective C. Here is a C example that calculates all the components you want based on IP address and netmask

http://lpccomp.bc.ca/netmask/netmask.c

Pierre-Luc Simard
+2  A: 

http://lpccomp.bc.ca/netmask/netmask.c That was exactly what I was looking for. Thanks to all of you.

Kolja