-
new to unix sockets
hey everybody!
i am experimenting with unix sockets and having some fun. i thought it would be good if i joined these forums to ask some questions....
so my first code sample is this...
Code:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char *argv[])
{
struct hostent *h;
if (argc != 3)
{
fprintf(stderr, "Usage: tel [HOST] [IP]\n");
exit(1);
}
h = gethostbyname(argv[1]);
if (h == NULL)
{
herror("gethostbyname");
exit(1);
}
char *ip = inet_ntoa(*((struct in_addr *)h->h_addr));
int port = *argv[2];
printf("IP : %s\n", ip);
printf("Port: %d\n", port);
int sockfd;
struct sockaddr_in dest_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(port);
dest_addr.sin_addr.s_addr = inet_addr( ip);
connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(struct sockaddr));
return 0;
}
now i know your are all laffing at how ugly and poorly coded this is but keep in mind that i aint that advanced. it keeps printf()'ing me that i am connecting on port 56 or 55 or whatever it is it's not argv[2]. any ideas? also you can see i am trying to create a telnet typeof utility so if you could maybe direct me as what to do that'd be great. thx guys
oh and btw i use linux with g++ to compile and it compiles fine.
-
Well, the problem is here:
Code:
int port = *argv[2];
because port is an integer but argv[2] is actually a string.
Use atoi():
Code:
int port = atoi(argv[2]);
Oh, BTW, the usage error, I'd change `IP' to `Port' ;)
-
yeah thanx man that did it...
now how much / kinda what would i have to add after connect to make this work like telnet would. recv() ing or something more complex....thxf
-
Read the telnet RFC - telnet expects some sort of control characters, I don't really know.
But basically, to read and recv data you'd use the following calls on a stream connected socket:
recv(2) - to receive data
send(2) - to send data
Code:
while(1) {
recv(fd,buf,sizeof(buf),0);
puts(buf);
fgets(stdin,buf,sizeof(buf));
send(fd,buf,strlen(buf),0);
}
this isn't the greatest way obviously, but just an example.