Reputation: 187
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.
Upvotes: 0
Views: 1657
Reputation: 6218
You also need to set servAdr.sin_family = AF_INET
before connecting.
If connection fail, better use perror()
to print the error.
Upvotes: 1
Reputation: 409146
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.
Upvotes: 2