Binding a udp socket to a port(on the local machine)

Jonathan Marler via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Apr 23 11:04:03 PDT 2017


On Saturday, 22 April 2017 at 21:24:33 UTC, Chainingsolid wrote:
> I couldn't figure out how to make a udp socket bound to a port 
> of my choosing on the local machine, to use for listening for 
> incoming connections.

I assume you meant "incoming datagrams" and not "incoming 
connections".

import std.stdio, std.socket;

void main()
{
     bool ipv6;
     ushort port = 1000;

     Address bindAddress;
     if(ipv6)
     {
         bindAddress = new 
Internet6Address(Internet6Address.ADDR_ANY, port);
     }
     else
     {
         bindAddress = new 
InternetAddress(InternetAddress.ADDR_ANY, port);
     }


     Socket udpSocket = new Socket(bindAddress.addressFamily, 
SocketType.DGRAM, ProtocolType.UDP);
     udpSocket.bind(bindAddress);
     writefln("listening for udp datagrams on port %s", port);

     ubyte[3000] buffer;
     while(true)
     {
         Address from;
         auto length = udpSocket.receiveFrom(buffer, from);
         writefln("received %s byte datagram from %s", length, 
from);
     }
}


More information about the Digitalmars-d-learn mailing list