Networking: getaddrinfo using different ports

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • kardon33
    New Member
    • May 2007
    • 158

    #1

    Networking: getaddrinfo using different ports

    My program sends commands to a different computer running a udp server.

    My problem is that each different node is running on a different udp port and the code needs to take that into account by allowing the port to change depending on a int variable.

    The to code snippets ive provided show what i got working and what i think should work but doesn't.

    This Works.
    Code:
       
       const char* po = "49240";
    
        if ((rv = getaddrinfo(lightIp, po, &hints, &servinfo)) != 0) {
            fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    
        }
    This does not work.
    Code:
       
      
         udpPort = 49240;
         const char* po = (char*)udpPort;
    
    
        if ((rv = getaddrinfo(lightIp, po, &hints, &servinfo)) != 0) {
            fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    
        }
  • jkmyoung
    Recognized Expert Top Contributor
    • Mar 2006
    • 2057

    #2
    It looks like you're casting 49240 as a memory address. udpPort appears to be an integer, not a char*.

    You might want:
    udpPort = "49240";
    const char* po = (char*) &udpPort;

    Comment

    • kardon33
      New Member
      • May 2007
      • 158

      #3
      OK but how would you take an integer (udpPort) containing the number 49240 and set it to something that getaddrinfo could use? I got close with (const char* po = "49240"; ) but i haven't been able to get that to be dynamic using a variable.

      Thanks for the help.

      Comment

      • jkmyoung
        Recognized Expert Top Contributor
        • Mar 2006
        • 2057

        #4
        Can you use the itoa function? http://www.cplusplus.com/reference/c.../cstdlib/itoa/

        Comment

        • kardon33
          New Member
          • May 2007
          • 158

          #5
          I was finally able to get it working with the fallowing code:

          Code:
             int udpPort = 12312;
             char buf[5];
             sprintf(buf,"%d",udpPort);
             po = (char*) &buf;
          
              if ((rv = getaddrinfo(lightIp, po, &hints, &servinfo)) != 0) {
                  fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
              }

          Comment

          Working...