Created
May 3, 2019 13:34
-
-
Save cuu/15ebc39a47708d9b84e1a0fc1aec40d0 to your computer and use it in GitHub Desktop.
simple_irc.c
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <netdb.h> | |
#include <sys/types.h> | |
#include <netinet/in.h> | |
#include <sys/socket.h> | |
#include <unistd.h> | |
#define PORT 6667 | |
#define MAX_BUFF 4096 | |
int main(int argc,char*argv[]) { | |
int sockfd; | |
int connected = 0; // Used to loop the program | |
char* server; // network address | |
char* nick = "NICK Somebot\r\n"; // NICK raw | |
char* user = "USER Somebot 0 * :a c bot\r\n"; // USER raw | |
char* join = "JOIN #gameshell\r\n"; | |
sockfd = -1; | |
struct sockaddr_in addr; | |
struct hostent *host; | |
if (argc != 2) { | |
printf("default connect to localhost\n"); | |
server = "127.0.0.1"; | |
}else { | |
server = argv[1]; | |
} | |
if( (host = gethostbyname(server))==NULL) { | |
herror("gethostbyname"); | |
exit(1); | |
} | |
/** Fill the members of the socket structs required to connect **/ | |
addr.sin_addr.s_addr = *(unsigned long*)host->h_addr; | |
addr.sin_family = AF_INET; | |
addr.sin_port = htons(PORT); | |
if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ) { | |
perror("socket"); | |
exit(1); | |
} | |
/** Connect to address **/ | |
if( connect(sockfd, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1) { | |
perror("connect");exit(1); | |
} | |
printf("Connecting to: %s\n",server); | |
send(sockfd,nick,strlen(nick), 0); // Converts nick string to c-array and sends it to server | |
printf("Sent: %s to server\n",nick); | |
send(sockfd, user, strlen(user), 0); | |
printf("Sent: %s to server\n",user); | |
send(sockfd, join, strlen(join),0); | |
printf("Sent: %s to server\n", join); | |
char sockbuff[MAX_BUFF]; | |
int numbytes; | |
while (connected < 1) { | |
memset(&sockbuff, 0, sizeof(sockbuff)); | |
if( (numbytes = recv(sockfd, sockbuff, MAX_BUFF, 0)) == -1) { | |
perror("recv"); | |
exit(1); | |
} | |
sockbuff[numbytes] = '\0'; | |
printf("%s",sockbuff); | |
} | |
close(sockfd); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment