Binding to a certain port

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

  1. macrumors newbie

    Joined:
    Jun 3, 2008
    #1
    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

    Server:
    Code:
    - (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);
                    return;
                }
    
                // Find out what port number was chosen.
                if (getsockname(fdForListening, (struct sockaddr *)&serverAddress, &namelen) < 0) {
                    close(fdForListening);
                    return;
                }
    
                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];
                }
            }
        }
    
    And
    Client:
    Code:
    - (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;
    
                        break;
                    case AF_INET6:
                        // PictureSharing server doesn't support IPv6
                        return;
                }
            }   
    
            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 {
                    close(socketToRemoteServer);
                }
            }
        }
    }
    
     
  2. macrumors regular

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

    example:

    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. thread starter macrumors newbie

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

    yeroen

    Joined:
    Mar 8, 2007
    Location:
    Cambridge, MA
    #4
    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:

    http://www.gnu.org/software/libtool/manual/libc/Byte-Order.html
     
  5. thread starter macrumors newbie

    Joined:
    Jun 3, 2008
    #5
    I tried that but still didnt work Any Suggestions
     

Share This Page