PDA

View Full Version : Socket Programming Introduction Source Code



Lynux-Penguin
04-29-2002, 11:35 PM
BROUGHT TO YOU BY
http://www.linuxsocket.org/

soooo many people have asked or had problems with BASIC Socket Programming, might as well post a template source code right?


#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#define PORT_HTTP 81
#define PORT_TIME 13
#define PORT_FTP 21
#define SERVER_ADDR "127.0.0.1"
#define MAXBUF 1024

int main(int argc, char* argv[])
{ int acc;
int sockfd;
struct sockaddr_in dest;
char buffer[MAXBUF];

/* Open socket for streaming */
if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("Socket");
exit(errno);
}
/* Init Server Address/port struct */
bzero(&dest,sizeof(dest));
dest.sin_family = AF_INET;
if(argv[1] == NULL)
dest.sin_port = htons(PORT_FTP);
else
{
scanf("%d",&acc);
dest.sin_port = htons(acc);
}
if ( inet_aton(SERVER_ADDR, &dest.sin_addr.s_addr) == 0)
{
perror(SERVER_ADDR);
exit(errno);
}
if( connect(sockfd, (struct sockaddr*)&dest,sizeof(dest)) != 0)
{
perror("Connect ");
exit(errno);
}

bzero(buffer,MAXBUF);
recv(sockfd,buffer,sizeof(buffer),0);
printf("%s",buffer);

close(sockfd);
return 0;
}


Slightly modified because I am working on a scanner but here is some code that opens up FTP and stuff...
When I finish the scanner, I will post that too.

Deckard
04-30-2002, 05:32 AM
Er, just some thoughts:


#define PORT_HTTP 81 /* Port 80 is the reserved HTTP port */

bzero(&dest,sizeof(dest)); /* bzero() has been deprecated. Use memset(). */


Also, what is this?

bzero(buffer,MAXBUF);
recv(sockfd,buffer,sizeof(buffer),0);
printf("%s",buffer);
Your first use of buffer is to zero it out. Save yourself the function call and initialize 'buffer' with:
char buffer[MAXBUF] = { 0 };Since you know the size of the buffer (MAXBUF), why call sizeof()? Also, how will the user know if recv() fails?


Here is a socket tutorial (http://neworder.box.sk/newsread.php?newsid=2844) written a while back that goes into more detail.

Lynux-Penguin
04-30-2002, 05:29 PM
This isn't my source code
it is Linux SOcket's
Mine is:
http://cyber.homeunix.net:81/c/scan.c

I am still new to Network Programming but I am a SEMI_PRO at Kernel Modules...

Still need to find more time to read all the information out there, thanks, when I rewrote my client.c (Linux Socket's name for that program) I noticed that too, well some things