Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <strings.h>
- #include <errno.h>
- #include <ifaddrs.h>
- #include <netdb.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #define PORT 3550
- #define BACKLOG 2 /* Max allowed connections */
- int main(int argc, char *argv[])
- {
- /* Get local address */
- struct ifaddrs *ifaddr, *ifa;
- char host[512] = {0};
- if (getifaddrs(&ifaddr) == -1) {
- printf("error getting local IP address: %i\n", strerror(errno));
- } else {
- for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
- getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);
- if((strcmp(ifa->ifa_name,"lo")!=0) && (ifa->ifa_addr->sa_family == AF_INET) ) {
- printf(" Interface : <%s>\n", ifa->ifa_name );
- printf(" Address : <%s>\n", host);
- }
- }
- freeifaddrs(ifaddr);
- }
- int fd, fd2; /* file descriptors */
- struct sockaddr_in server;
- /* server address info */
- struct sockaddr_in client;
- /* client address info */
- int sin_size;
- if ((fd=socket(AF_INET, SOCK_STREAM, 0)) == -1 ) {
- printf("socket() error\n");
- exit(-1);
- }
- server.sin_family = AF_INET;
- server.sin_port = htons(PORT);
- server.sin_addr.s_addr = INADDR_ANY;
- /* connect to any IP*/
- bzero(&(server.sin_zero),8);
- if (bind(fd,(struct sockaddr*)&server,
- sizeof(struct sockaddr))==-1) {
- printf("bind() error\n");
- exit(-1);
- }
- if (listen(fd,BACKLOG) == -1) {
- printf("listen() error\n");
- exit(-1);
- }
- while(1) {
- sin_size = sizeof(struct sockaddr_in);
- printf ("\nWaiting for a 3DS...\n");
- if ((fd2 = accept(fd,(struct sockaddr *)&client,
- &sin_size))==-1) {
- printf("error en accept()\n");
- exit(-1);
- }
- printf("We got connection from: %s\n",
- inet_ntoa(client.sin_addr) );
- /* show client IP */
- send(fd2,"Welcome to my server.\n",22,0);
- /* send a message to the client */
- close(fd2); /* close fd2 */
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement