0

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.

2
  • 2
    Instead of using printf to print the error, use perror as it will print a more complete error message based on errno. Commented Mar 1, 2013 at 12:49
  • Consider reading a good book like advancedlinuxprogramming.com Commented Mar 1, 2013 at 12:58

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much. That was silly of me. Sorry for wasting your time.
@user2051577 Don't worry about it. Everyone looks "silly" when they're new. It'll get better. :)
1

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

1 Comment

Thank you very much sorry for your trouble!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.