Linux shell implementation of socket programming simple example

Source: Internet
Author: User

When it comes to sockets, people who have learned the basics of internet have heard that he is the abstraction of TCP/IP, he is the portal of the Internet world, it is everywhere.

Learn the socket programming, means to be able to more deep control of your traffic, and then look at the Python urllib* or php curl, it is pediatrics!

I. Some nouns

Address Family

Address type, protocol family, may be the following

Socket.af_inet---> IPv4 addresses.
SOCKET.AF_INET6---> IPV6 addresses.
Socket.af_unix---> UNIX domain sockets (for example,/var/run/mysqld/mysqld.sock is a example).
SOCKET.AF_IPX---> IPX addresses.
Socktype

Sock type

Socket. Sock_stream---> Streaming sockets, for TCP
Socket. SOCK_DGRAM---> Datagram sockets, for UDP

Other

Parameters Take value Value Description
Address Family Af_inet 2 IPv4
Af_inet6 23 IPv6
Af_unspec 0 Protocol irrelevant
Protocol Numbers Protocol Number Ipproto_ip 0 IP protocol
Ipproto_ipv4 4 IPv4
Ipproto_ipv6 41 IPv6
Ipproto_udp 17 Udp
Ipproto_tcp 6 Tcp
Socktype sock Type Sock_stream 1 Flow
Sock_dgram 2 Data Report
Ai_flags Ai_passive 1 Passive, used for bind, typically used for server sockets
Ai_canonname 2 The canonical name used to return the host
  
Ai_numerichost 4 Address is a number string


Ii. Simple Examples

Examples from official documents are very basic.

Service side

# Echo Server Program
Import socket

HOST = ' 127.0.0.1 ' # symbolic name meaning all available interfaces
Port = 50007 # arbitrary non-privileged Port
s = socket.socket (socket.af_inet, socket. SOCK_STREAM)
S.bind (HOST, PORT)
S.listen (1)
conn, addr = S.accept ()
print ' Connected by ', addr
While 1:
data = CONN.RECV (1024)
If not data:break
Conn.sendall (data)
Conn.close ()
Client

# Echo Client program
Import socket

host = ' localhost ' # The remote host
Port = 50007 # The same port as used by the server
s = socket.socket (socket.af_inet, socket. SOCK_STREAM)
S.connect (HOST, PORT)
S.sendall (' Hello, World ')
data = S.RECV (1024)
S.close ()
print ' Received ', repr (data)


Iii. more complex examples

Service side

Unlike before, support for IPV6

# Echo Server Program
Import socket
Import Sys

HOST = None # symbolic name meaning all available interfaces
Port = 50007 # arbitrary non-privileged Port
s = None
For res in Socket.getaddrinfo (HOST, PORT, Socket.af_unspec,
Socket. Sock_stream, 0, socket. ai_passive):
AF, Socktype, Proto, canonname, sa = res
Try
s = Socket.socket (AF, Socktype, Proto)
Except Socket.error as msg:
s = None
Continue
Try
S.bind (SA)
S.listen (1)
Except Socket.error as msg:
S.close ()
s = None
Continue
Break
If S is None:
print ' could not open socket '
Sys.exit (1)
conn, addr = S.accept ()
print ' Connected by ', addr
While 1:
data = CONN.RECV (1024)
If not data:break
Conn.send (data)
Conn.close ()


Client

# Echo Client program
Import socket
Import Sys

host = ' localhost ' # The remote host
Port = 50007 # The same port as used by the server
s = None
For res in Socket.getaddrinfo (HOST, PORT, Socket.af_unspec, socket. SOCK_STREAM):
AF, Socktype, Proto, canonname, sa = res
Try
s = Socket.socket (AF, Socktype, Proto)
Except Socket.error as msg:
s = None
Continue
Try
S.connect (SA)
Except Socket.error as msg:
S.close ()
s = None
Continue
Break
If S is None:
print ' could not open socket '
Sys.exit (1)
S.sendall (' Hello, World ')
data = S.RECV (1024)
S.close ()
print ' Received ', repr (data)

Above we mentioned the basic form of socket programming, this section we enhance the performance of the service side!

#!/usr/bin/env python

Import socket, threading

Class Clientthread (threading. Thread):

def __init__ (self, IP, port, socket):
Threading. Thread.__init__ (self)
Self.ip = IP
Self.port = Port
Self.socket = socket
print [+] New thread started for "+ip+": "+str (port)

def run (self):
Print "Connection from:" +ip+ ":" +str (port)

Self.socket.send ("\nwelcome to the server\n\n")

data = "Dummydata"

While Len (data):
data = SELF.SOCKET.RECV (2048)
Print "Client Sent:" +data
Self.socket.send ("You sent me:" +data)

Print "Client disconnected ..."

Host = "0.0.0.0"
Port = 9999

Tcpsock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Tcpsock.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR, 1)

Tcpsock.bind ((Host,port))
Threads = []


While True:
Tcpsock.listen (4)
Print "\nlistening for incoming connections ..."
(Clientsock, (IP, port) = Tcpsock.accept ()
Newthread = Clientthread (IP, port, Clientsock)
Newthread.start ()
Threads.append (Newthread)

For T in Threads:
T.join ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.