Daily Background Service Development is inevitable. However, the tcp client is actually quite cool to write, with various errors returned and various exception judgments .... In general, we do not need to write a robust client. We just need a usable client to test whether the server is correct.
Here we will introduce a simple and easy-to-use Method: Using Bash to operate socket! Cool, isn't it?
Man Bash: Find the TCP keyword and you can see the following content:
2 |
If host is a valid hostname or Internet address, and port is an integer port number or service name, bash attempts to open a TCP connection to the corresponding socket. |
Replace the host and port with the IP address and port to be connected, and then you can establish a TCP connection. As follows:
1 |
Exec 3 <>/dev/tcp/10.6.221.149/9865 |
A readable and writable socket connection to 10.6.221.149: 9865 is established above.
3 is the socket FD after the specified connection. Since 0, 1, and 2 are occupied by stdin, stdout, and stderr, the available FD can start at least from 3.
Changing an IP address to a domain name is also supported, for example
1 |
Exec 3 <>/dev/tcp/www.xx.com/9865 |
Note: "<>" do not have spaces before and after, or an error will occur.
Sending a request is actually very simple, just like writing data to a file. For example
1 |
Exec"Hello world ." > & 3 |
If you want to send an HTTP request, you can do this:
1 |
Echo-e"Get/crossdomain. xml HTTP/1.1 \ r \ nhost: www.xx.com \ r \ n" > & 3 |
The binary request can be sent as follows:
Bin_data is a written Binary Package data file.
The response from the read server is similar to that from the read file. You can write it like this:
After the connection is closed in the background, the cat command automatically ends.
If the binary content is read, you can use hexdump to view it.
The read results are as follows:
Here,-N indicates that hexdump stops reading 31 bytes. For a good programming habit, remember to close the connection.
To disable the above socket connection, you can write as follows:
1 |
Exec 3> &-# disable write and cannot send a request again |
2 |
Exec 3 <&-# Close Reading. No more results can be returned. |
Of course, if you do not close it, it may not be a big problem. When the bash script is executed, the connection will be automatically closed.
The following is a client I used for testing:
2 |
Exec 3 <>/dev/tcp/10.6.221.149/9865 |
3 |
Echo"<Policy-file-request>" > & 3 |
Look, this tcp client is better than the client that comes out of the C language.
Code It's not just a star. Using Bash to operate UDP is similar. Of course, if you are very good at it, you can use Bash to write a server and try it. If you try it out, share the Code with me. From: http://www.cnblogs.com/hokyhu/archive/2011/09/27/2193489.html