Socket Programming Fundamentals

Choose a study mode

Play Quiz
Study Flashcards
Spaced Repetition
Chat to Lesson

Podcast

Play an AI-generated podcast conversation about this lesson
Download our mobile app to listen on the go
Get App

Questions and Answers

Which layer of the OSI model do sockets primarily operate within to facilitate data transmission?

  • Network Layer
  • Application Layer
  • Data Link Layer
  • Transport Layer (correct)

What benefit does layering provide to application programmers when using sockets?

  • Requires programmers to implement their own routing protocols.
  • Automatically handles WiFi encryption.
  • Abstracts away the complexities of routing, Ethernet frames, and WiFi encryption. (correct)
  • Exposes low-level details of the network.

Which of the following best describes what lower layers need to know for data transmission?

  • Destination IP address and port number. (correct)
  • The implementation details of the application.
  • The application's user interface preferences.
  • The programming language used by the application.

What is a socket primarily used for?

<p>Establishing a two-way communication link between networked programs. (B)</p>
Signup and view all the answers

In the context of socket programming, what does the term 'de facto standard' imply about sockets?

<p>Sockets have become standard through widespread use and acceptance. (A)</p>
Signup and view all the answers

Which of the following is NOT a typical application of sockets?

<p>Directly manipulating hardware devices. (A)</p>
Signup and view all the answers

What is a key characteristic of stream sockets?

<p>Connection-oriented communication ensuring sequence and error checking, typically with TCP. (B)</p>
Signup and view all the answers

Which protocol is typically used with datagram sockets?

<p>UDP (A)</p>
Signup and view all the answers

What is a primary reason for using sockets over higher-level libraries?

<p>Standard API for connecting processes locally and over a network. (D)</p>
Signup and view all the answers

Which operating systems provide compatibility with sockets?

<p>Linux, UNIX, Windows, and macOS (D)</p>
Signup and view all the answers

Why might a developer choose NOT to use sockets and instead opt for higher-level libraries?

<p>Sockets require more effort in defining protocols and handling security. (D)</p>
Signup and view all the answers

In socket communication, what information is contained within the 'connection socket pair'?

<p>Both the client's and server's IP addresses and port numbers. (A)</p>
Signup and view all the answers

What is the fundamental difference between a 'passive' and an 'active' socket?

<p>Active sockets initiate connections, while passive sockets passively wait for incoming requests. (D)</p>
Signup and view all the answers

Which sequence of actions accurately reflects the steps a server typically performs when using sockets?

<p>Setup, Transfer Data, Close (B)</p>
Signup and view all the answers

In the context of setting up a socket, what is the purpose of the bind() function?

<p>To associate a socket with a specific local address and port. (A)</p>
Signup and view all the answers

What does the listen() function do in socket programming?

<p>It allows the socket to listen for incoming connection requests. (D)</p>
Signup and view all the answers

What is the significance of the accept() function in server-side socket programming?

<p>It accepts a pending connection request, creating a new socket for the connection. (C)</p>
Signup and view all the answers

In the sockaddr_in structure, what is the purpose of the sin_family field?

<p>Defines the address family, such as AF_INET for IPv4. (C)</p>
Signup and view all the answers

What is the role of the htons() function in socket programming?

<p>It converts a port number from host byte order to network byte order. (C)</p>
Signup and view all the answers

In the context of the socket() function, what is the significance of the protocol argument being set to 0?

<p>It allows the system to choose a suitable default protocol based on the specified type. (B)</p>
Signup and view all the answers

What is the primary purpose of the INADDR_ANY constant when binding a socket?

<p>It enables the socket to listen on all available network interfaces. (D)</p>
Signup and view all the answers

If the listen() function is called with a backlog parameter of 5, what does this signify?

<p>The queue for pending connections can hold up to 5 connection requests. (D)</p>
Signup and view all the answers

What does the return value of the accept() function represent?

<p>The file descriptor of the newly created socket for the accepted connection. (D)</p>
Signup and view all the answers

In a client-server model using sockets, which action does the client perform to initiate a connection after setting up its socket?

<p>Connects to the server's address and port. (A)</p>
Signup and view all the answers

When a client calls the gethostbyname() function, what type of information is it trying to retrieve?

<p>The server's IP address. (A)</p>
Signup and view all the answers

What is the purpose of the send() and recv() functions in socket programming?

<p>To read and write data to and from a socket. (A)</p>
Signup and view all the answers

What is one key difference between using send()/recv() versus read()/write() for data transfer over sockets?

<p><code>send()</code> and <code>recv()</code> provide flags for more specific socket-level control. (D)</p>
Signup and view all the answers

In a typical client-server interaction using sockets, which side usually calls connect()?

<p>The client (C)</p>
Signup and view all the answers

Which of the following is a valid reason to use stream sockets over datagram sockets?

<p>When the order and reliability of data are critical. (D)</p>
Signup and view all the answers

Which function is responsible for accepting a connection request in a server application?

<p><code>accept()</code> (C)</p>
Signup and view all the answers

If a server needs to handle multiple client connections concurrently, what approach is typically used in conjunction with sockets?

<p>Multithreading or multiprocessing, where each thread or process handles one connection. (C)</p>
Signup and view all the answers

When using TCP sockets, what is the correct sequence of operations to gracefully close a connection?

<p>Both the client and server must call <code>close()</code> on their respective sockets. (C)</p>
Signup and view all the answers

What could be a potential drawback of using connectionless datagram sockets?

<p>Potential for packet loss or out-of-order delivery (A)</p>
Signup and view all the answers

Consider the following code snippet where an error is occurring: sockfd = socket(AF_INET, SOCK_STREAM, 0); and sockfd returns -1; what does this generally indicate?

<p>There was an error creating the socket. (B)</p>
Signup and view all the answers

Why is it often necessary to convert the IP address from presentation (human-readable) format to network format using inet_pton (or similar) before storing it in sockaddr_in?

<p>Network format ensures the address will be correctly interpreted regardless of system architecture. (A)</p>
Signup and view all the answers

Imagine a scenario where a server is designed to handle a high volume of simultaneous connections and uses a non-blocking socket approach with select() or epoll(). If the server suddenly stops responding to new connection attempts while still actively serving existing connections, what is the most likely cause?

<p>The server has exhausted its available file descriptors, preventing new sockets from being created. (D)</p>
Signup and view all the answers

A networked service suffers intermittent connection drops. Wireshark captures reveal TCP RST packets being sent from the server immediately after receiving data from clients. Increasing the SO_RCVBUF socket option on the server has no effect. What is the most likely cause?

<p>The application is crashing after receiving the data, causing the OS to send a reset packet immediately. (A)</p>
Signup and view all the answers

Flashcards

What is a Socket?

An endpoint of a two-way communication link between two networked programs.

Why Sockets?

The standard API for connecting processes, locally or over a network.

What's in a socket?

It is the connection between client and server contains client address, server address and port number.

Stream Sockets

Connection-oriented sockets using TCP for reliable data transfer.

Signup and view all the flashcards

Datagram Sockets

Connectionless sockets using UDP for fast but unreliable data transfer.

Signup and view all the flashcards

socket() function

A function that returns a file descriptor for the socket.

Signup and view all the flashcards

bind() function

A function that assigns an address to a socket.

Signup and view all the flashcards

listen() function

A function to listen for incoming connections on a socket.

Signup and view all the flashcards

accept() function

A function to accept an incoming connection, creating a new socket.

Signup and view all the flashcards

Socket Domain

AF_INET (IPv4) or AF_INET6 (IPv6)

Signup and view all the flashcards

Socket Type

SOCK_STREAM (TCP) or SOCK_DGRAM (UDP)

Signup and view all the flashcards

connect() function

A function that initiates a connection to a server.

Signup and view all the flashcards

send() / recv()

Transfer data using original socket functions.

Signup and view all the flashcards

read() / write()

Transfer data considering socket as a file.

Signup and view all the flashcards

Study Notes

  • Socket Programming is presented by Tran Giang Son, [email protected] of the ICT Department, USTH

Contents

  • What is a socket?
  • Why use sockets?
  • What is in a socket?
  • How to use sockets?

Why Layering?

  • It's similar to application layering.
  • Application programmer responsibilities:
    • Not concerned with routing.
    • Not concerned with Ethernet frames.
    • Not concerned with WiFi WPA2 encryption.
    • Not concerned with reliability implementations.
  • Application programmer tasks:
    • Passes data down.
    • Focuses on the application logic.
  • Lower layers need to know:
    • Destination (where to), specified by hostname (resolved with gethostbyname()) or IP address.
    • Service, indicated by port number.

Socket: What?

  • A socket is an endpoint of a two-way communication link between two networked programs.
  • Sockets are represented by a file descriptor after creation, based on the Unix philosophy that "everything is a file."
  • Sockets are the de facto standard for TCP/UDP but they replaced the following:
    • NetBIOS / NetBEUI
    • IPX / SPX

Socket: Applications

  • Most network applications use sockets.
  • Sockets are used to:
    • Send messages.
    • Share data like images, music, videos.
    • Facilitate Interprocess Communication (IPC)

Socket: Which Types?

  • Stream sockets: connection-oriented with TCP
    • Make a connection.
    • Transfer data.
    • Close connection.
    • Ensure sequence, error checking.
    • Example: YouTube video.
  • Datagram sockets: connectionless with UDP
    • Transfer data without explicitly making a connection.
    • Example: DNS.

Socket: Why?

  • Sockets are the standard API for connecting processes locally or over a network.
  • Compatibility: widely supported on Linux / UNIX, Windows, and macOS.
  • They are low-level, minimizing data transfer and providing speed with very little overhead.
  • Sockets are Customizable, flexible, self-defined protocol

Why NOT Socket Over Higher-Level Libraries?

  • Sockets are low-level and require more effort.
  • They require the definition of protocol, message boundaries, data representation, and security.
  • Session control including authentication must be implemented.

What's In A Socket?

  • Client socket address: 128.2.194.242:3479
  • Client host address: 128.2.194.242
  • Server socket address: 208.216.181.15:80
  • Server host address: 208.216.181.15
  • FTP Server (port 21)
  • HTTP Server (port 80)
  • Connection socket pair (128.2.194.242:3479, 208.216.181.15:80)

Overview

  • Server:
    • Passively waits.
    • Uses a passive socket.
  • Client:
    • Initiates the connection.
    • Uses an active socket.

Steps

  • Setup to find remote host and the service
  • Transfer Data
    • Send/Receive using write() / read()
  • Close

Server Overview

  • The server process involves:
    • socket() call
    • bind() associate a socket with a port number
    • Buy cable
    • Connect cable
    • Power on machine
    • listen() to incoming requests
    • accept() connections
  • This equates to a landline phone.

Socket: Important Struct

struct sockaddr_in {
    short sin_family;  // e.g., AF_INET
    unsigned short sin_port;  // e.g., htons(3490)
    struct in_addr sin_addr;  // see struct in_addr, below
    char sin_zero[8];  // zero this if you want to
};
struct in_addr {
    unsigned long s_addr;  // load with inet_aton()
};

Server: Setup Socket

int socket(int domain, int type, int protocol);
  • domain: AF_INET (IPv4) or AF_INET6 (IPv6)
  • type: SOCK_STREAM (TCP) or SOCK_DGRAM (UDP)
  • protocol: 0

Example:

int sockfd = socket(AF_INET, SOCK_STREAM, 0);

Server: Binding bind()

int bind(int sockfd,
         const struct sockaddr *bind_addr,
         socklen_t addrlen);
  • sockfd: file descriptor returned by socket()
  • bind_addr: a struct sockaddr_in for IPv4
  • addrlen: size of the struct pointed by bind_addr

Server: Example for socket() and bind()

struct sockaddr_in saddr;
int sockfd;
unsigned short port = 80;

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    printf("Error creating socket\n");
    ...
}

memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(INADDR_ANY);
saddr.sin_port = htons(port);

if (bind(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) {
    printf("Error binding\n");
    ...
}

Server: Listen To Incoming Connections listen()

int listen(int sockfd, int backlog);
  • sockfd: file descriptor that socket() returned
  • backlog: number of pending connections to queue
  • Example: listen(sockfd, 10);

Server: Accept an Incoming Connection accept()

int accept(int sockfd,
           struct sockaddr *addr,
           socklen_t *addrlen);
  • The server must explicitly accept incoming connections.
  • sockfd: file descriptor that socket() returned
  • addr: pointer to store client address
  • addrlen: size of addr
  • Returns a file descriptor for the connected socket
  • Example:
    int client = accept(sockfd,
                     (struct sockaddr_in *) &caddr, &clen);
    

Server: Example for listen() and accept()

if (listen(sockfd, 5) < 0) {
    printf("Error listening\n");
    ...
}

clen = sizeof(caddr);
if ((clientfd = accept(sockfd,
                       (struct sockaddr *) &caddr, &clen)) < 0) {
    printf("Error accepting connection\n");
    ...
}

Server: Complete Example

int sockfd, clen, clientfd;
struct sockaddr_in saddr, caddr;
unsigned short port = 80;

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    printf("Error creating socket\n");
    ...
}

memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl(INADDR_ANY);
saddr.sin_port = htons(port);

if ((bind(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) {
    printf("Error binding\n");
    ...
}

if (listen(sockfd, 5) < 0) {
    printf("Error listening\n");
    ...
}

clen = sizeof(caddr);
if ((clientfd = accept(sockfd, (struct sockaddr *) &caddr, &clen)) < 0) {
    printf("Error accepting connection\n");
    ...
}

Practical Work 3: Server Setup

  • Write a new program in C named "03.practical.work.server.setup.c".
  • The server should:
    • Listen to TCP port 8784 (USTH in a T9 dial pad!).
    • Bind to all possible interfaces.
    • Print a message when a client connects to it.
  • Deploy to VPS (Virtual Private Server).
  • Test the connection using telnet or nc
  • Push C program to corresponding forked GitHub repository.

Client: Setup Socket

  • Similar to server's
int socket(int domain, int type, int protocol);
  • domain: AF_INET (IPv4) or AF_INET6 (IPv6)
  • type: SOCK_STREAM (TCP) or SOCK_DGRAM (UDP)
  • protocol: 0
  • Example: int sockfd = socket(AF_INET, SOCK_STREAM, 0);

Client: Connect to Server connect()

int connect(int sockfd,
            const struct sockaddr *saddr,
            socklen_t addrlen);
  • sockfd: file descriptor that socket() returned.
  • addr: pointer to store server address.
  • addrlen: size of addr.
  • Example: connect(sockfd, (struct sockaddr *) &saddr, sizeof(saddr))

Client: Complete Example

struct sockaddr_in saddr;
struct hostent *h;
int sockfd;
unsigned short port = 80;

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
    printf("Error creating socket\n");
    ...
}

if ((h = gethostbyname("ict.usth.edu.vn")) == NULL) {
    printf("Unknown host\n");
    ...
}

memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
memcpy((char *) &saddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length);
saddr.sin_port = htons(port);

if (connect(sockfd, (struct sockaddr *) &saddr, sizeof(saddr)) < 0) {
    printf("Cannot connect\n");
    ...
}

Practical Work 4: Client Setup

  • Write a new program in C named "04.practical.work.client.setup.c".
  • The client should:
    • Get the server hostname from program arguments.
    • Ask for hostname from STDIN if no argument is provided.
    • Resolve IP address and print to STDOUT.
    • Connect to that server, TCP port 8784
    • Print a message if it connects to the server successfully.
  • Test the connection from the client to the server on VPS.
  • Push C program to corresponding forked GitHub repository.

Data Transfer: Overview

  • Two common ways for data transfer:
    • send() / recv()
      • Original socket functions.
      • Specific to sockets with "flags".
    • read() / write()
      • Consider socket as a file.
      • Generic functions.
  • Use either pair, don't mix.

Data Transfer: recv() and send()

ssize_t recv(int socket, void *buffer, size_t length, int flags);
ssize_t send(int socket, const void *buffer, size_t length, int flags);
  • socket: use socket file descriptor returned by socket() or accept()
  • buffer: buffer to read from / write to
  • length: size of the allocated buffer (recv()) and length of the content (send())
  • flags: specific "settings" for the request.
  • Example:
recv(sockfd, buffer, sizeof(buffer), 0);
send(sockfd, "hello world!\n", 13, 0);

Data Transfer: read() and write()

ssize_t read(int fd, void *buf, size_t len);
ssize_t write(int fd, const void *buf, size_t len);
  • fd: file descriptor, use socket file descriptor returned by socket() or accept()
  • buf: buffer to read from / write to
  • len: size of the allocated buffer (read()) and length of the content (write())
  • Example:
read(sockfd, buffer, sizeof(buffer));
write(sockfd, "hello world!\n", 13);

Data Transfer: Taking Turn

  • Client:
while (condition) {
    scanf() from STDIN;
    send() to server;
    recv() from server;
    printf() to STDOUT;
}
  • Server:
while (condition) {
    recv() from client;
    printf() to STDOUT;
    scanf() from STDIN;
    send() to client;
}

Practical Work 5: Data Transfer, Taking Turn

  • Copy your client and server code from the 4th practical work to:
    • "05.practical.work.server.turn.c"
    • "05.practical.work.client.turn.c"
  • Improve the client and server to build a chat system:
    • Input from STDIN.
    • Send to the other side.
    • Output received data to STDOUT.
    • The client and server take turns.
  • Test the system between your laptop and VPS.
  • Push your C programs to the corresponding forked GitHub repository.

Studying That Suits You

Use AI to generate personalized quizzes and flashcards to suit your learning preferences.

Quiz Team

Related Documents

Socket Programming PDF

More Like This

Networking Concepts Overview
10 questions
Introduction to Sockets in Networking
26 questions
Réseaux et Protocoles de Communication
48 questions
Use Quizgecko on...
Browser
Browser