Binding to a certain port

Discussion in 'Mac Programming' started by fuzeman, Jun 16, 2008.

  1. fuzeman macrumors newbie

    Jun 3, 2008
    I have a script that binds to a random port for use with a Server and Client but I really need to have The Server And Client always run for example on port 5156 just a Example I dont want the Client to Bring up Other services on other Ports just port 5156 for example how will i be able to do that this is the Code i guess you must change stuff in this code cause it has Binding and Socket etc
    Thanks Alot By the way im new to xcode so im just learning :D

    - (IBAction)toggleSharing:(id)sender {
        uint16_t chosenPort;
        if(!listeningSocket) {
            // Here, create the socket from traditional BSD socket calls, and then set up an NSFileHandle with
            //that to listen for incoming connections.
            int fdForListening;
            struct sockaddr_in serverAddress;
            int namelen = sizeof(serverAddress);
            // In order to use NSFileHandle's acceptConnectionInBackgroundAndNotify method, we need to create a
            // file descriptor that is itself a socket, bind that socket, and then set it up for listening. At this
            // point, it's ready to be handed off to acceptConnectionInBackgroundAndNotify.
            if((fdForListening = socket(AF_INET, SOCK_STREAM, 0)) > 0) {
                memset(&serverAddress, 0, sizeof(serverAddress));
                serverAddress.sin_family = AF_INET;
                serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
                serverAddress.sin_port = 0;
                // Allow the kernel to choose a random port number by passing in 0 for the port.
                if (bind(fdForListening, (struct sockaddr *)&serverAddress, namelen) < 0) {
                    close (fdForListening);
                // Find out what port number was chosen.
                if (getsockname(fdForListening, (struct sockaddr *)&serverAddress, &namelen) < 0) {
                chosenPort = ntohs(serverAddress.sin_port);
                // Once we're here, we know bind must have returned, so we can start the listen
                if(listen(fdForListening, 1) == 0) {
                    listeningSocket = [[NSFileHandle alloc] initWithFileDescriptor:fdForListening closeOnDealloc:YES];
    - (void)netServiceDidResolveAddress:(NSNetService *)sender {
        if ([[sender addresses] count] > 0) {
            NSData * address;
            struct sockaddr * socketAddress;
            NSString * ipAddressString = nil;
            NSString * portString = nil;
            int socketToRemoteServer;
            char buffer[256];
            int index;
            // Iterate through addresses until we find an IPv4 address
            for (index = 0; index < [[sender addresses] count]; index++) {
                address = [[sender addresses] objectAtIndex:index];
                socketAddress = (struct sockaddr *)[address bytes];
                if (socketAddress->sa_family == AF_INET) break;
            // Be sure to include <netinet/in.h> and <arpa/inet.h> or else you'll get compile errors.
            if (socketAddress) {
                switch(socketAddress->sa_family) {
                    case AF_INET:
                        if (inet_ntop(AF_INET, &((struct sockaddr_in *)socketAddress)->sin_addr, buffer, sizeof(buffer))) {
                            ipAddressString = [NSString stringWithCString:buffer];
                            portString = [NSString stringWithFormat:@"%d", ntohs(((struct sockaddr_in *)socketAddress)->sin_port)];
                        // Cancel the resolve now that we have an IPv4 address.
                        [sender stop];
                        [sender release];
                        serviceBeingResolved = nil;
                    case AF_INET6:
                        // PictureSharing server doesn't support IPv6
            if (ipAddressString) [ipAddressField setStringValue:ipAddressString];
            if (portString) [portField setStringValue:portString];
            socketToRemoteServer = socket(AF_INET, SOCK_STREAM, 0);
            if(socketToRemoteServer > 0) {
                NSFileHandle * remoteConnection = [[NSFileHandle alloc] initWithFileDescriptor:socketToRemoteServer closeOnDealloc:YES];
                if(remoteConnection) {
                    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(readAllTheData:) name:NSFileHandleReadToEndOfFileCompletionNotification object:remoteConnection];
                    if(connect(socketToRemoteServer, (struct sockaddr *)socketAddress, sizeof(*socketAddress)) == 0) {
                        [remoteConnection readToEndOfFileInBackgroundAndNotify];
                } else {
  2. friarbayliff macrumors regular

    Jul 20, 2004
    MN / IN
    I think it's a simple matter of assigning serverAddress.sin_port to the port you want.


    serverAddress.sin_port = 5156;

    The client is a little different (I'm a little rusty with these things), but googling something like 'c sockets' should give you plenty of resources on network programming.
  3. fuzeman thread starter macrumors newbie

    Jun 3, 2008
    Thats what i thought tried that Server ended up on port: 9236 How will i change the port its annoying :(
  4. yeroen macrumors 6502a


    Mar 8, 2007
    Cambridge, MA
    You need to be aware of endian issues when you're programming network sockets:

    5156 in hex is 0x1424

    Now watch what happens when we swap the bytes:

    5156 = 0x1424 <---> 0x2414 = 9236

    For port numbers, use ntohs(3) or htons(3) to swap bytes. You can read more about it here:
  5. fuzeman thread starter macrumors newbie

    Jun 3, 2008
    I tried that but still didnt work Any Suggestions

Share This Page