This is a skeleton of something I am currently using. I got it from bejee's socket programming tutorial. Google it. anyways, this should pretty much compile and run (if I didn't miss any errors. I don't have a compiler here), at least is linux eviroment. If you are using windows, google that tutorial and you can learn the differences. Hope this helps.
Here is the basic layout:
#define FILESIZE 100000 /* size of download -- change as needed */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <netdb.h> /* Important to gethostname */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, char **argv)
{
int sockfd;
struct sockaddr_in dest_addr;
struct hostent *host;
char *stream;
/* Don't forget to check the args */
/* Build the GET command for the download */
b_send = (char *)malloc(31*sizeof(char));
strcpy(b_send, "GET file.html\r\n"); /* file.html is the your file.html */
/* Resolve the Hostname */
if((host = gethostbyname(argv[1])) == NULL )
{
herror("gethostbyname()");
exit(1);
}
/* Open the socket */
sockfd = socket(host->h_addrtype, SOCK_STREAM, 0);
if (sockfd == -1)
{
printf("socket() failed.\n");
exit(1);
}
/* Build the Destination Address Struct */
memset(&(dest_addr.sin_fam
dest_addr.sin_family = AF_INET;
dest_addr.sin_port = htons(DEST_PORT);
memcpy(&dest_addr.sin_addr
/* Connect to destination Address */
if ((connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(dest_addr))) == -1)
{
perror("connect()");
printf(" %s : %d\n", sys_errlist[errno], errno);
exit(1);
}
/* Send GET /..... */
if((bytes_sent = send(sockfd, b_send, strlen(b_send), 0)) == -1)
{
perror("send()");
}
/* Allocate the receive memory and open the out file */
b_recv = malloc(1500);
stream = malloc(FILESIZE);
strcpy(stream, "");
/* Receive the information in blocks of 1500 bytes */
while((bytes_recv = recv(sockfd, b_recv, 1500, 0)) > 0)
{
strcat(b_recv, sizeof(char), bytes_recv, ofp);
}
if(bytes_recv == -1)
{
perror("recv()");
}
close(sockfd);
free(b_send);
free(b_recv);
free(stream);
return 0;
}
Main Topics
Browse All Topics





by: KdoPosted on 2005-05-18 at 19:15:32ID: 14033112
Hi kinko899,
Basically, you want to generate three strings from the first one.
http://1.2.3.4/file.htm
The three strings are:
http:
1.2.3.4
file.htm
There are quite a few ways to do this. Here's a simple way that should server you well.
char *p1, *p2, *p3;
char *String = "http://1.2.3.4/file.htm";
p1 = strtok (String, "/"); /* returns http: */
strtok (NULL, "/"); /* there are back-to-back slashes. Skip this one. */
p2 = strok (NULL, "/"); /* returns 1.2.3.4 */
p3 = strtok (NULL, "/"); /* returns file.htm */
That's all there is to it.
Good Luck!
Kent