简体   繁体   中英

C program for client using socket on ubuntu linux end not running

I am new to socket programming. I tried to execute a program today. My intention was to check whether the server is available or not. Expecting the output "Failed!" but my program doesn't seem to work. The code shows no error during compilation which makes me wonder if I am using the Linux API correctly. The following is my code...

#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>

int main()
    {
    char servIP[]="127.0.0.1";
    char check[]="check";
    int SrvConnect,ret;
    struct sockaddr_in servAdr;
    //printf("Test");
    SrvConnect=socket(AF_INET,SOCK_STREAM,0);
    servAdr.sin_addr.s_addr=inet_addr(servIP);
    servAdr.sin_port=htons(1000);
    ret=sendto(SrvConnect,&check,sizeof(check),0,(struct sockaddr *)&servAdr,sizeof(servAdr));
    if(ret==-1)
        printf("\nFailed!\n");
    //printf("Test");
    close(SrvConnect);
    }

I have tried placing several output statement at the beginning and end of the code itself (now commented). But even those lines do not execute. Please don't mind if it is a silly mistake. A am really new to this and I have nobody to guide me. Thank You for reading.

The problem is that you have created a TCP socket. TCP sockets needs to be connected to the server before you can send anything. Try calling connect first to connect to the server, and the use write or send to send data.

You also need to set servAdr.sin_family = AF_INET before connecting. If connection fail, better use perror() to print the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM