Sockets em C Muito Massa
Ta ai so uma parte do Código o restante ta na link logo abaixo vlw
/libs diversas para tratar entrada, saida, memoria, string, erros...
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "errno.h"
#include "unistd.h"
//lib padrão para uso da socket
#include "netinet/in.h"
#include "arpa/inet.h"
#include "sys/types.h"
#include "sys/socket.h"
// lib para usar para converter host para ip
#include "netdb.h"
#define MAXSIZE 800
#define MAX 500
int main() {
int sockfd,n;
char *url,buff[MAXSIZE],sBuff[MAXSIZE],host[MAX],page[MAX],enter[MAX];
/*
no protocolo http o cliente manda dados com a info
GET /index.html HTTP/1.1
Host: www.site.com
para tal feito ficaria em C
GET /index.html HTTP/1.1\nHost: www.site.com\t \n\n
Peguei entrada um link http extraimos host e dados do GET
com sscanf,também pode ser feito com split ou regex,bom estraido
dados usei strcat para concatenar as variaveis alfanumericas
*/
char getpage[MAX]="GET /";
// struct do netdb para converter host para ip
struct hostent *ip;
// struct da socket
struct sockaddr_in end;
//pegamos entrada do usuario
printf("digite um link: ");
fgets(enter, sizeof(enter), stdin);
enter[strlen(enter)-1] = '\0';
//extraimos host e local da pagina
sscanf(enter, "http://%99[^/]/%99[^\n]", host, page);
printf("DNS = \"%s\"\n", host);
printf("Page = \"%s\"\n\n", page);
strcat(page," HTTP/1.1\nHost: ");
strcat(page,host);
strcat(page,"\t \n\n");
// função da lib netdb.h para converter ai nosso host para IP
ip = gethostbyname(host);
url=inet_ntoa(*(struct in_addr *)ip->h_addr);
strcat(getpage,page);
printf("%s",getpage);
/*
separamos buff para pegar resposta do server
mas antes preenchemos a memoria com \0
usamos sbuff para armazenar dados do envio
*/
memset(buff,'\0',sizeof(char)*MAXSIZE);
memset(sBuff,'\0',sizeof(char)*MAXSIZE);
strcpy(sBuff,getpage);
// condições simples em caso de erro
if( (sockfd=socket(AF_INET,SOCK_STREAM,0)) < 0 ){
perror("socket");
return errno;
}
// definimos a porta usado no caso 80
/*
sin familia
+ AF_INET (ARPA INTERNET PROTOCOLS) - "A mais usada"
+ AF_UNIX (UNIX INTERNET PROTOCOLS)
+ AF_ISO (ISO PROTOCOLS)
+ AF_NS (XEROX NETWORK SYSTEM PROTOCOLS)
*/
end.sin_family=AF_INET;
end.sin_port=htons(80);/* Aqui é o seguinte:
htons significa "host to network short", como
é short trabalha com 2 bytes,mas ha ainda
outros tipos como: htonl("host to network
long",4 bytes), ntós("network to host
short",2 bytes), ntól("network to host
long", 4 bytes). */
if( inet_pton(AF_INET,url,&end.sin_addr) < 0){
perror("inet_pton");
return errno;
}
memset(end.sin_zero,'\0',8);
if(connect(sockfd,(struct sockaddr*)&end,sizeof(struct sockaddr)) < 0){
perror("connect");
return errno;
}
if( (send(sockfd, sBuff, strlen(sBuff), 0)) < 0){
perror("send");
close(sockfd);
return errno;
}
// recebe a resposta e mostra saida
while((n=read(sockfd,buff,MAXSIZE)) > 0) fprintf(stdout,"%s",buff);
close(sockfd);
return 0;
}
Link para codigo
Blogger Comentario