1. Trang chủ
  2. » Công Nghệ Thông Tin

Linux Socket Programming by Example PHẦN 1 pot

52 420 2

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 52
Dung lượng 2,76 MB

Nội dung

Linux Socket Programming by Example Warren W. Gay Part I: Basic Socket Concepts 6 Chapter 1. Introducing Sockets 7 A Brief Historical Introduction 7 Understanding Sockets 8 Comparing Sockets to Pipes 12 Creating Sockets 12 Performing I/O on Sockets 18 Closing Sockets 21 Writing a Client/Server Example 26 Chapter 2. Domains and Address Families 35 Nameless Sockets 35 Understanding Domains 36 Forming Socket Addresses 37 Forming Local Addresses 39 Forming Internet (IPv4) Socket Addresses 48 Specifying an X.25 Address 57 Specifying Other Address Families 60 The AF_UNSPEC Address Family 64 Chapter 3. Address Conversion Functions 65 Internet IP Numbers 66 Allocating IP Addresses 73 Manipulating IP Numbers 75 Chapter 4. Socket Types and Protocols 94 Specifying the Domain of a Socket 94 Using the socket(2) Function 96 Choosing a Socket Type 97 Choosing a Protocol 103 Socket Domain and Type Summary 109 Other Linux-Supported Protocols 110 Chapter 5. Binding Addresses to a Socket 118 The Purpose of the bind(2) Function 118 Using the bind(2) Function 119 Obtaining the Socket Address 122 Interfaces and Addressing 131 Chapter 6. Connectionless-Oriented Protocols 135 Linux Socket Programming by Example - Warren W. Gay 1 The Methods of Communication 136 Performing Input/Output of Datagrams 138 Writing a UDP Datagram Server 143 Writing a UDP Datagram Client 148 Testing the Datagram Client and Server 153 Chapter 7. Connection-Oriented Protocols for Clients 160 Reviewing the Methods of Communication 160 Internet Services 162 Consulting the /etc/protocols File 170 Writing a TCP/IP Client Program 175 Using connect(2) on SOCK_DGRAM Sockets 182 What's Next 183 Chapter 8. Connection-Oriented Protocols for Servers 183 Understanding the Role of the Server 184 The listen(2) Function 186 The accept(2) Function Call 189 Writing a TCP/IP Server 192 Modifying the Client Program 200 Chapter 9. Hostname and Network Name Lookups 203 Understanding the Need for Names 204 Using the uname(2) Function 204 Obtaining Hostnames and Domain Names 208 Resolving Remote Addresses 210 Part II: Advanced Socket Programming 227 Chapter 10. Using Standard I/O on Sockets 227 Understanding the Need for Standard I/O 228 Associating a Socket with a Stream 229 Closing a Socket Stream 230 Using Separate Read and Write Streams 231 Winding Up Communications 233 Handling Interrupts 237 Defining Buffer Operation 240 Applying FILE Streams to Sockets 243 What's Next 265 Chapter 11. Concurrent Client Servers 265 Understanding the Multiple-Client Problem 266 Overview of Server Functions 267 Using fork(2) to Service Multiple Clients 272 Linux Socket Programming by Example - Warren W. Gay 2 Designing Servers That Use select(2) 279 Applying select(2) to a Server 284 What's Next 298 Chapter 12. Socket Options 298 Getting Socket Options 299 Setting Socket Options 303 Retrieving the Socket Type (SO_TYPE) 308 Setting the SO_REUSEADDR Option 310 Setting the SO_LINGER Option 313 Setting the SO_KEEPALIVE Option 316 Setting the SO_BROADCAST Option 318 Setting the SO_OOBINLINE Option 319 Options SO_PASSCRED and SO_PEERCRED 319 What's Next 320 Chapter 13. Broadcasting with UDP 320 Understanding Broadcast Addresses 320 Broadcasting from a Server 323 Receiving Broadcasts 329 Demonstrating the Broadcasts 332 Broadcasting to a Network 334 What's Next 337 Chapter 14. Out-of-Band Data 337 Defining Out-of-Band 338 Understanding the Need for Out-of-Band Data 338 Sockets and Out-of-Band Data 339 Variations in Implementation 340 Using Out-of-Band Data 341 Understanding the Urgent Pointer 355 Receiving Out-of-Band Data Inline 360 Limitations of the Urgent Mode Pointer 366 What's Next 368 Chapter 15. Using the inetd Daemon 368 Steps Common to Most Servers 369 Introducing inetd 369 Implementing a Simple stream tcp Server 374 Datagram Servers with inetd 380 What's Next 382 Chapter 16. Network Security Programming 382 Linux Socket Programming by Example - Warren W. Gay 3 Defining Security 383 The Challenges of Security 383 Identifying Friend or Foe 386 Securing inetd Servers 388 Installing Wrapper and Server Programs 393 Introducing the Client Program 404 Installing and Testing the Wrapper 407 What's Next 414 Chapter 17. Passing Credentials and File Descriptors 415 Problem Statement 415 Introducing Ancillary Data 416 Introducing I/O Vectors 417 The sendmsg(2) and recvmsg(2) Functions 420 Ancillary Data Structures and Macros 424 Presenting an Ancillary Data Example 431 Testing the Socket Server 455 What's Next 457 Chapter 18. A Practical Network Project 458 Problem Statement 458 Solving the Quote Service Problem 458 Examining the Quote Server Program 462 Fetching Quotations via get_tickinfo() 469 Broadcasting Quotes via broadcast() 477 Examining the Client Program 478 Compiling and Running the Demonstration 483 What's Next 487 Appendixes 487 Appendix A. Socket Function Quick Reference 488 Socket-Specific Functions 488 Socket Addressing 489 int getpeername(int s, struct sockaddr *name, socklen_t *namelen) Reading of Sockets 489 Writing to Sockets 490 Other Socket I/O 492 Controlling Sockets 492 Network Support Functions 494 Standard I/O Support 495 Hostname Support 496 Linux Socket Programming by Example - Warren W. Gay 4 Appendix B. Socket-Related Structures Reference 496 Socket Address Structures 497 Miscellaneous Structures 499 I/O-Related Structures 500 Appendix C. Useful Network Tables 500 Appendix glossary 502 Linux Socket Programming by Example - Warren W. Gay 5 Part I: Basic Socket Concepts Introducing Sockets Domains and Address Families Address Conversion Functions Socket Types and Protocols Binding Addresses to a Socket Connectionless-Oriented Protocols Connection-Oriented Protocols for Clients Connection-Oriented Protocols for Servers Hostname and Network Name Lookups Linux Socket Programming by Example - Warren W. Gay 6 Chapter 1. Introducing Sockets Friday, October 4, 1957, marked the beginning of a startling new era. The Soviet Union had launched the world's first artificial satellite into the Earth's orbit, known as Sputnik. Approximately the size of a basketball, this satellite took 98 minutes to orbit the Earth. Anyone with a shortwave radio was able to hear it during overhead passes, at a frequency of approximately 40.002Mhz. Who would have imagined at that time, that this would later spawn the beginnings of TCP/IP and the Internet? In this chapter you will be introduced to • A brief history of how sockets were developed • The essence of sockets • How sockets are referenced by the Linux kernel and application programs • An introductory example of a socket C program Chapter 1. Introducing Sockets A Brief Historical Introduction Eisenhower's response to the Sputnik threat was to approach Congress on January 7, 1958, for the startup funds necessary for the Advanced Research Projects Agency (ARPA). At that time, government agencies were required to buy computers from different manufacturers each time they made a purchase, to maintain fairness. The new ARPA organization soon found that they had a collection of machines that spoke completely different languages. Sometime after 1962, J. C. R. Licklider conceived of the idea that computers should be able to communicate with one another, even if they were "highly individualistic." During the 1960s, the ARPAnet was being conceived and developed by a number of talented people. The humble beginning of the ARPAnet was to become the Internet that we know of today. Eventually ARPA was folded into the Defense Linux Socket Programming by Example - Warren W. Gay 7 Advanced Research Projects Agency (DARPA). Overlapping with the development of ARPAnet, UNIX development was beginning in 1969. The University of California, Berkeley (UCB) later developed their own flavor of UNIX, which was known as BSD. DARPA wanted to divest itself of the business of networking, and so DARPA provided funding to UCB in 1979, to further develop the ARPAnet. In 1982, 4.1BSD and 4.2BSD versions of UNIX were released by UCB that included a TCP/IP network implementation. The network socket concepts and interfaces that you will learn about in this book are based upon the work done by UCB. Linux draws upon this rich heritage, and so you'll learn about the Linux specific implementation of the BSD socket interface in this book. Figure 1.1 is provided as a time line overview of the history behind the socket interface. Figure 1.1. According to the time line, BSD sockets were developed 24 years after the formation of ARPA. Understanding Sockets It is important that you have an understanding of some of the concepts behind the socket interface before you try to apply them. This section outlines some of the high level concepts surrounding the sockets themselves. Defining a Socket To communicate with someone using a telephone, you must pick up the handset, dial the other party's telephone number, and wait for them to answer. While you speak to that other party, there are two endpoints of communication established: • Your telephone, at your location • The remote party's telephone, at his location As long as both of you communicate, there are two endpoints involved, with a line of communication in between them. Figure 1.2 shows an illustration of two telephones as endpoints, each connected to the other, through the telephone network. Linux Socket Programming by Example - Warren W. Gay 8 Figure 1.2. Without the telephone network, each endpoint of a telephone line is nothing more than a plastic box. A socket under Linux, is quite similar to a telephone. Soc kets represent endpoints in a line of communication. In between the endpoints exists the data communications network. Sockets are like telephones in another way. For you to telephone someone, you dial the telephone number of the party you want to contact. Sockets have network addresses instead of telephone numbers. By indicating the address of the remote socket, your program can establish a line of communication between your local socket and that remote endpoint. Socket addresses are discussed in Chapter 2, "Domains and Address Families." You can conclude then, that a socket is merely an endpoint in communication. There are a number of Linux function calls that operate on sockets, and you learn about all of them in this book. Using Sockets You might think that Linux sockets are treated specially, because you've already learned that sockets have a collection of specific functions that operate on them. Although it is true that sockets have some special qualities, they are very similar to file descriptors that you should already be familiar with. Note Any reference to a function name like pipe(2) means that you should have online documentation (man pages) on your Linux Linux Socket Programming by Example - Warren W. Gay 9 system for that function. For information about pipe(2) for example, you can enter the command: $ man 2 pipe where the 2 represents the manual section number, and the function name can be used as the name of the manual page. Although the section number is often optional, there are many cases where you must specify it in order to obtain the correct information. For example, when you open a file using the Linux open(2) call, you are returned a file descriptor if the open(2) function is successful. After you have this file descriptor, your program uses it to read(2), write(2), lseek(2), and close(2) the specific file that was opened. Similarly, a socket, when it is created, is just like a file descriptor. You can use the same file I/O functions to read, write, and close that socket. You learn in Chapter 15, "Using the inetd Daemon," that sockets can be used for standard input (file unit 0), standard output (file unit 1), or standard error (file unit 2). Note Sockets are referenced by file unit numbers in the same way that opened files are. These unit numbers share the same "number space"—for example, you cannot have both a socket with unit number 4 and an open file on unit number 4 at the same time. There are some differences, however, between sockets and opened files. The following list highlights some of these differences: • You cannot lseek(2) on a socket (this restriction also applies to pipes). • Sockets can have addresses associated with them. Files and pipes do not have network addresses. • Sockets have different option capabilities that can be queried and set using ioctl(2). Linux Socket Programming by Example - Warren W. Gay 10 [...]... fflush(stdout); 80: 81: /* 82: * Write a request to the server: 83: */ Linux Socket Programming by Example - Warren W Gay 28 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 10 0: 10 1: 10 2: 10 3: 10 4: 10 5: 10 6: 10 7: 10 8: 10 9: 11 0: 11 1: 11 2: 11 3: 11 4: 11 5: 11 6: 11 7: 11 8: 11 9: 12 0: 12 1: 12 2: 12 3: 12 4: 12 5: 12 6: 12 7: 12 8: 12 9: 13 0: 13 1: 13 2: 13 3: 13 4: 13 5: 13 6: 13 7: 13 8: z = write(s [1] ,msgp,mlen);... Linux Socket Programming by Example - Warren W Gay 29 13 9: close(s [1] ); /* Client uses s [1] */ 14 0: s [1] = -1; /* Forget this descriptor */ 14 1: 14 2: /* 14 3: * Wait for a request from the client: 14 4: */ 14 5: z = read(s[0],buf,sizeof buf); 14 6: 14 7: if ( z < 0 ) { 14 8: fprintf(stderr,"%s: read(2)\n", 14 9: strerror(errno)); 15 0: exit (1) ; 15 1: } 15 2: 15 3: /* 15 4: * Put a null byte at the end of the 15 5:... < 0 ) { 17 5: fprintf(stderr,"%s: write(2)\n", 17 6: strerror(errno)); 17 7: exit (1) ; 17 8: } 17 9: 18 0: /* 18 1: * Close our end of the socket: 18 2: */ 18 3: close(s[0]); 18 4: 18 5: /* 18 6: * Wait for the child process to exit 18 7: * See text 18 8: */ 18 9: waitpid(chpid,&status,0); 19 0: } 19 1: 19 2: return 0; 19 3: } Linux Socket Programming by Example - Warren W Gay 30 The program shown in Listing 1. 3 can be... Listing 1. 2 shows an example that performs some reads and writes upon sockets in both directions Listing 1. 2 01LST02.c Example Performing I/O on a Socket Pair 1: 2: 3: 4: 5: 6: 7: 8: /* Listing 1. 2: * * Example performing I/O on a Socket Pair: */ #include #include #include #include Linux Socket Programming by Example - Warren W Gay 18 9: 10 : 11 : 12 : 13 : 14 : 15 : 16 :... /01lst 01 Note Be certain to watch the case of the filename when entering the executable filename at the command prompt The executable filenames chosen use lowercase letters The results of running the program are as follows (with line numbers added for reference purposes): 1: $ /01lst 01 Linux Socket Programming by Example - Warren W Gay 16 2: 3: 4: 5: 6: 7: 8: 9: 10 : 11 : 12 : 13 : 14 : 15 : 16 : 17 : 18 : 19 :... client: 15 6: */ 15 7: buf[z] = 0; 15 8: 15 9: /* 16 0: * Now perform the server function on the 16 1: * received message: 16 2: */ 16 3: time(&td); /* Get current time */ 16 4: 16 5: strftime(txbuf,sizeof txbuf, /* Buffer */ 16 6: buf, /* Input format */ 16 7: localtime(&td)); /* Input time */ 16 8: 16 9: /* 17 0: * Send back the response to client: 17 1: */ 17 2: z = write(s[0],txbuf,strlen(txbuf)); 17 3: 17 4: if... … 789 @00000030 unix 1 [] STREAM … 549 @00000023 unix 1 [] STREAM 10 32 662/01lst 01 unix 1 [] STREAM 10 31 662/01lst 01 unix 1 [] STREAM … 793 /dev/log unix 1 [] STREAM … 582 /dev/log unix 1 [] STREAM … 574 /dev/log unix 1 [] STREAM … 572 /dev/log unix 1 [] STREAM … 408 /dev/log $ The executable program 01lst 01 is invoked in line 1 in the output shown Lines 2 and 3 show that the socket pair was opened... Function 1: 2: 3: 4: 5: 6: 7: 8: 9: 10 : 11 : 12 : 13 : 14 : 15 : 16 : 17 : 18 : 19 : 20: 21: 22: 23: 24: 25: 26: 27: /* Listing 1. 1: * * Example of socketpair(2) function: */ #include #include #include #include #include #include #include int main(int argc,char **argv) { int z; /* Status return code */ int s[2]; /* Pair of sockets... lines 98 to 10 1 7 The client now calls read(2) to wait for a response message (line 10 6) The client process will wait indefinitely here until a response arrives Errors are reported in lines 10 7 to 11 1 8 A null byte is placed at the end of the received response in line Linux Socket Programming by Example - Warren W Gay 32 9 The received response is reported in lines 12 2 to 12 3 10 .The client socket is... socketpair(2) and fork(2) 1: 2: 3: 4: 5: 6: 7: 8: 9: 10 : 11 : 12 : 13 : 14 : 15 : 16 : 17 : 18 : 19 : 20: 21: 22: 23: 24: 25: 26: 27: 28: /* Listing 1. 3 * * Client/Server Example Using socketpair(2) * and fork(2): */ #include #include #include #include #include #include #include #include #include /* * As of RedHat-6.0, . @00000020 11 : unix 0 [ ] STREAM … 11 7 - @00000 011 12 : unix 1 [ ] STREAM … 789 - @00000030 13 : unix 1 [ ] STREAM … 549 - @00000023 14 : unix 1 [ ] STREAM 10 32 662/01lst 01 15: unix 1 [ ] STREAM 10 31 662/01lst 01 16:. <string.h> 10 : #include <sys/types.h> 11 : #include <sys /socket. h> 12 : 13 : int 14 : main(int argc,char **argv) { 15 : int z; /* Status return code */ 16 : int s[2]; /* Pair of sockets */ 17 : 18 :. Other Linux- Supported Protocols 11 0 Chapter 5. Binding Addresses to a Socket 11 8 The Purpose of the bind(2) Function 11 8 Using the bind(2) Function 11 9 Obtaining the Socket Address 12 2 Interfaces

Ngày đăng: 12/08/2014, 21:20

TỪ KHÓA LIÊN QUAN

w