Get network subnet and broadcast addresses

Share your advanced PureBasic knowledge/code with the community.
User avatar
Joakim Christiansen
Addict
Addict
Posts: 2452
Joined: Wed Dec 22, 2004 4:12 pm
Location: Norway
Contact:

Get network subnet and broadcast addresses

Post by Joakim Christiansen »

Code: Select all

EnableExplicit

Procedure.l stringToIP(ip$)
  ProcedureReturn MakeIPAddress(Val(StringField(ip$,1,".")),Val(StringField(ip$,2,".")),Val(StringField(ip$,3,".")),Val(StringField(ip$,4,".")))
EndProcedure
Procedure.s getSubnetAddress(ip$,subnetMask$)
  Protected ip.l, subnetMask.l, subnet.l
  ip         = stringToIP(ip$)
  subnetMask = stringToIP(subnetMask$)
  subnet = ip & subnetMask
  ProcedureReturn IPString(subnet)
EndProcedure
Procedure.s getBroadcastAddress(ip$,subnetMask$)
  Protected ip.l, subnetMask.l, subnet.l, broadcastAddress.l
  ip         = stringToIP(ip$)
  subnetMask = stringToIP(subnetMask$)
  subnet = ip & subnetMask
  broadcastAddress = subnet | ~subnetMask
  ProcedureReturn IPString(broadcastAddress)
EndProcedure

Debug getSubnetAddress("192.168.0.1","255.255.255.0")
Debug getBroadcastAddress("192.168.0.1","255.255.255.0")
Based on information here:
http://www.shunsoft.net/ipcalc/help/index.html
I like logic, hence I dislike humans but love computers.