The UNIX and Linux Forums  
Hello and Welcome from United States to the UNIX and Linux Forums! Thank You for Visiting and Joining Our Global Community.

Go Back   The UNIX and Linux Forums > Top Forums > High Level Programming
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #1 (permalink)  
Old 04-28-2007
Stevhp Stevhp is offline
Registered User
  
 

Join Date: Mar 2007
Posts: 9
Problem Connecting to Socket

Can anyone help? I'm trying to write a program which will write to a socket. I can get the server to run, but always get an error when I try to connect.

It gives me an error at the "connect" command.

It's probably a simple error, but I can't seem to find it.



#include <sys/socket.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv[]) {

int outgoing, newSock, i;
struct sockaddr_in sad;
char buf;
char action[255];
FILE *command;

if(argc < 4) {
printf("Wrong command line arguments");
return 1;
}

outgoing=socket(PF_INET,SOCK_STREAM,0);
if(outgoing == -1) {
printf("Unable to create socket");
return 1;
}

sad.sin_family=AF_INET;
sad.sin_port=atoi(argv[2]);
sad.sin_addr.s_addr=inet_addr(argv[1]);

if(connect(outgoing, (struct sockaddr *) &sad, sizeof(struct sockaddr_in)) == -1) {
printf("Cannot connect to address %s port %s", argv[1], argv[2]);
return 1;
}

send(outgoing, argv[3], strlen(argv[3]), 0);
while(recv(outgoing, &buf, 1, 0))
printf("%c", buf);

return 0;

}