290 likes | 472 Views
Introduction to Socket Programming Jeong, EunYoung ( notav at ndsl.kaist.edu). EE324 Programming Tutorial. Outline. Socket programming Editor ( emacs ) Compiling ( Makefile ) Debugging ( gdb ). Sockets. Sockets Abstraction for data communication
E N D
Introduction to Socket Programming Jeong, EunYoung (notavat ndsl.kaist.edu) EE324 Programming Tutorial
Outline • Socket programming • Editor (emacs) • Compiling (Makefile) • Debugging (gdb)
Sockets • Sockets • Abstraction for data communication • A process can send/receive data through sockets
Socket API • TCPsocket API • Stream sockets • Connection-oriented • 4 tuples (source IP, port, destination IP, port) • Reliable • UDP socket API • Datagram sockets • 2 tuples (source IP, port) • Unreliable
TCP Socket Programming • TCP socket programming • Server first listens for incoming connections • Client initiates the connection to the server • Server accepts the connection • Exchange data • Server sends “Hello, world!” to the client • Close connection • Reference: Beej’s guide to network programming • http://beej.us/guide/bgnet/output/html/multipage/clientserver.html
TCP Server Example /* create a socket */ sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sockfd < 0) { perror("socket"); return-1; } /* set the address family (IPv4), address (any address), port */ saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = INADDR_ANY; saddr.sin_port = htons(PORT); /* bind the address to the socket */ if (bind(sockfd, (structsockaddr *)&saddr, sizeof(structsockaddr_in))) { perror("bind"); close(sockfd); return -1; }
TCP Server Example /* listen connections */ if (listen(sockfd, BACKLOG) < 0) { perror("listen"); exit(1); } /* reap all dead processes */ sa.sa_handler = sigchld_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) { perror("sigaction"); exit(1); } printf("server: waiting for connections...\n");
TCP Server Example while (1) { // main accept() loop /* accept new connections from clients */ sin_size= sizeof(their_addr); new_fd= accept(sockfd, (structsockaddr *)&their_addr, &sin_size); if(new_fd == -1) { perror("accept"); continue; } inet_ntop(AF_INET, &their_addr.sin_addr, s, sizeof(s)); printf("server: got connection from %s\n", s); if(!fork()) { // this is the child process close(sockfd); // child doesn't need the listener if(send(new_fd, "Hello, world!", 13, 0) == -1) perror("send"); close(new_fd); exit(0); } close(new_fd); // parent doesn't need this }
TCP Client Example /* get the server host entry */ hp = gethostbyname(argv[1]); if (hp == NULL) { perror("gethostbyname"); return -1; } /* create stream socket */ sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sockfd < 0) { perror("socket"); return -1; } /* set the destination address */ daddr.sin_family = AF_INET; memcpy(&daddr.sin_addr.s_addr, hp->h_addr, hp->h_length); daddr.sin_port = htons(PORT);
TCP Client Example /* connect to the destination */ if (connect(sockfd, (structsockaddr *)&daddr, sizeof(structsockaddr_in))) { close(sockfd); perror("connect"); return-1; } inet_ntop(AF_INET, &daddr.sin_addr, s, sizeof(s)); printf("client: connecting to %s\n", s); /* receive message sent from the server */ if ((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1) { perror("recv"); exit(1); } /* print the received message */ buf[numbytes] = '\0'; printf("client: received '%s'\n", buf); close(sockfd);
UDP Socket Programming • UDP socket programming • No connection establishment! • Server binds to a port (bind()) • Exchange data • Server waits for incoming messages (recvfrom()) • Client sends messages (sendto()) • Simple! • But there can be loss of data
UDP Listener Example /* create a socket */ sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sockfd < 0) { perror("socket"); return -1; } /* set the address family (IPv4), address (any address), port */ saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = INADDR_ANY; saddr.sin_port = htons(PORT); /* bind the address to the socket */ if (bind(sockfd, (structsockaddr *)&saddr, sizeof(structsockaddr_in))) { perror("bind"); close(sockfd); return -1; }
UDP Listener Example printf("listener: waiting to recvfrom...\n"); addr_len = sizeoftheir_addr; if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN - 1 , 0, (structsockaddr *)&their_addr, &addr_len)) == -1) { perror("recvfrom"); exit(1); } printf("listener: got packet from %s\n", inet_ntop(AF_INET, &their_addr.sin_addr, s, sizeof(s))); printf("listener: packet is %d bytes long\n", numbytes); buf[numbytes] = '\0'; printf("listener: packet contains \"%s\"\n", buf); close(sockfd);
UDP Talker Example /* get the server host entry */ hp = gethostbyname(argv[1]); if (hp == NULL) { perror("gethostbyname"); return -1; } /* create a socket */ sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (sockfd < 0) { perror("socket"); return -1; }
UDP Talker Example /* set the destination address */ daddr.sin_family = AF_INET; memcpy(&daddr.sin_addr.s_addr, hp->h_addr, hp->h_length); daddr.sin_port = htons(PORT); if ((numbytes = sendto(sockfd, argv[2], strlen(argv[2]), 0, (structsockaddr *)&daddr, sizeof(structsockaddr))) == -1) { perror("talker: sendto"); exit(1); } printf("talker: sent %d bytes to %s\n", numbytes, argv[1]); close(sockfd);
Emacs • Launching emacs • $ emacsserver.c • Notations • C-x: Ctrl + x, M-x: ESC followed by x (or Alt + x) • Moving around in buffers • Forward: →, C-f Backward: ←, C-b • Next line: ↓, C-n Previous line: ↑, C-p • Searching • C-s: forward search, C-r: backward search • Jumping • M-g g: go to the line
Emacs • Region • Marking: C-SPC • C-x h: Select all • M-h: Select paragraph • Killing • C-k: kill line, C-u 10 C-k: kill 10 lines • Yanking (Paste) • C-y: Yanks last killed text • Undo • C-/, C-_, C-x u
Emacs • Finally exit! • C-x C-c • For more detail • http://www.gnu.org/software/emacs/tour/ • http://cmgm.stanford.edu/classes/unix/emacs.html
Compiling • Simple compiling • g++ (source codes) –o (object name) • Ex) $ g++ server.c –o server • Ex) $ g++ a.cb.cd.c –o abd • Compile options • -g: for debugging • -Wall: show as many warnings as possible • -DNDEBUG: remove asserts when compiling • Ex) $ g++ -g –Wall server.c –o server
Makefile • Script for easier compilation • g++ main.cpp hello.cpp factorial.cpp -o hello -> make • Basic Makefile • Target: dependencies • [tab] system command • Example all: g++ main.cpp hello.cpp factorial.cpp -o hello Reference: http://mrbook.org/tutorials/make/
Using Dependencies • Build process • Compiler generates object files from source codes • Linker creates executable binary from the object files • Example all: hello hello: main.ofactorial.ohello.o g++ main.ofactorial.ohello.o main.o: main.cpp g++ -c main.cpp … clean: rm -rf*.o hello
Using Variables • Example CC=g++ CFLAGS=-g –Wall all: hello hello: main.ofactorial.ohello.o $(CC) main.ofactorial.ohello.o main.o: main.cpp $(CC) $(CFLAGS) -c main.cpp … clean: rm -rf*.o hello
Complete Example CC=g++ CFLAGS=-g –Wall LDFLAGS= SOURCES=main.cpp hello.cpp factorial.cpp OBJECTS=$(SOURCES:.cpp=.o) EXECUTABLE=hello all: $(SOURCES) $(EXECUTABLE) $(EXECUTABLE): $(OBJECTS) –o $@ $(CC) $(LDFLAGS) $(OBJECTS) –o $@ .cpp.o: $(CC) $(CFLAGS) –c $< -o $@ clean: rm-rf*.o $(EXECUTABLE)
gdb • Debugger • Helps pointing problem of your program Reference: http://www.cs.cmu.edu/~gilpin/tutorial/
Running with gdb • Running program • gdbmain • (gdb) run • Exiting • (gdb) quit
Inspecting Crashes • Exploring stack frames • backtrace (or bt): print backtrace of all stack frames • up: go to the stack frame called by this one • down: go to the stack frame called this one • help stack for more features • print: print value of expression • Ex) print item_to_remove • x: examine memory • Ex) x 0xffbef014
Conditional Breakpoints • Breakpoints • Make the program break at a certain point • break LinkedList<int>::remove • Or break main.cc:53 • Giving condition • Make the breakpoint only works on a certain condition • condition 1 item_to_remove==1 • Stepping • step: forward a line
Finding the Bug • Line 77: marker is set to 0 • Line 79: marker is accessed • Removing line 77 will make it work • For more information • http://www.cs.cmu.edu/~gilpin/tutorial/ • http://www.unknownroad.com/rtfm/gdbtut/ • http://www.cs.umd.edu/~srhuang/teaching/cmsc212/gdb-tutorial-handout.pdf