1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

problem establishing TCP socket

Discussion in 'C' started by gkkmath, Aug 28, 2010.

  1. gkkmath

    gkkmath New Member

    Aug 28, 2010
    Likes Received:
    Trophy Points:
    Hi Experts,

    I'm writing a C program (cut/paste below) to establish a TCP socket connection from my Mac Pro to a Windows XP-based test instrument sitting next to it over LAN (Ethernet). The program compiles without any warnings or errors. But executing the code using GNU Debugger, I can see it exits at 'exit(2)' which is the "if(connect(MySocket" line. There's no timeout, it just exits immediately.

    I compile using:
    gcc -g -Wall talk2me.c -o talk2me
    but I don't get any hints in the output nor when debugging at to what might be the issue.

    I'm sure the and port 5025 are correct (independently, using Matlab code I can communicate fine using these parameters). Any idea where else I could look to debug?

    Outside of the code itself, are there any other requirements (perhaps system-level) that need to be satisfied (like running the code from a certain directory, or setting a parameter in unix to allow connections, etc.)? It may be something obvious that I'm missing as I'm not that experienced in this.

    I can run a 'hello world' program fine, it that helps.


    int main(void)
    int MySocket;
    if((MySocket=socket(PF_INET,SOCK_STREAM,0))==-1) exit(1);
    struct in_addr {
            unsigned long s_addr;
    struct sockaddr_in {
            short int sin_family;                         // Address family
            unsigned short int sin_port;         // Port number
            struct in_addr sin_addr;                 // Internet address
            unsigned char sin_zero[8];                 // Padding
    struct sockaddr_in MyAddress;
    // Initialize the whole structure to zero
    memset(&MyAddress,0,sizeof(struct sockaddr_in));
    // Then set the individual fields
    MyAddress.sin_family=PF_INET;                 // IPv4
    MyAddress.sin_port=htons(5025);         // Port number used by instrument
    MyAddress.sin_addr.s_addr=inet_addr(""); // IP Address
    if(connect(MySocket,(struct sockaddr *) &MyAddress, 
            sizeof(struct sockaddr_in))==-1) exit(2);  
    // Send SCPI command
    if(send(MySocket,"*IDN?\n",6,0)==-1) exit(3);
    // Read response
    char buffer[200];
    int actual;
    if((actual=recv(MySocket,&buffer[0],200,0))==-1) exit(4);
    buffer[actual]=0; // Add zero character (C string)
    printf("Instrument ID: %s\n",buffer);
    // Close socket
    if(close(MySocket)==-1) exit(99);
    return 0;

Share This Page