Profile

Click to view full profile
Hi, I'm Veerapat Sriarunrungrueang, an expert in technology field, especially full stack web development and performance testing.This is my coding diary. I usually develop and keep code snippets or some tricks, and update to this diary when I have time. Nowadays, I've been giving counsel to many well-known firms in Thailand.
view more...
Showing posts with label Network. Show all posts
Showing posts with label Network. Show all posts

Tuesday, May 19, 2015

Archeblade Internet Server Configuration

To configure Archeblade server, do the following steps:
  1. by default Archeblade server use 3 ports starting with port 7777. For example, if the textbox in Port Num is 7777, it will use ports 7777-7779.
  2. Firewall: disabled or add Inbound Rules in Advance Firewall settings. Then, allow TDP for ports 7777-7779 and another one for UDP in the same ports.
  3. Configure your router for Port-Forwarding to receive incoming port 7777 to local port 7777 on your specific server ip address for both TCP and UDP.                      
  4. Do step 3 more for port 7778 and 7779.
  5. Done

Wednesday, July 2, 2014

Full restore using Windows Server Backup - Network path not found

To full restore from Network drive 1. A user that used to retrieve backup must gain full control all files and folders within that drive. 2. To gain full control, it is not only just gain full control from security tab. It must be included from Advanced menu in security tab then adding / changing an owner, full control permission for all childs, Auditing, and Effective Access to that user. 3. After completed, now, restored machine can full restore from Network drive if everything is done correctly. More information: 1. How to use Windows Server backup http://blogs.technet.com/b/dpm/archive/2011/11/01/data-protection-manager-2010-and-bare-metal-restore.aspx. 2. Resolve Network Path was not found http://blogs.technet.com/b/dpm/archive/2011/11/01/data-protection-manager-2010-and-bare-metal-restore.aspx 3. How to set IP in Command Prompt (during boot) http://www.howtogeek.com/103190/change-your-ip-address-from-the-command-prompt/http://technet.microsoft.com/en-us/library/ee441257(v=ws.10).aspx

Saturday, May 31, 2014

How to setup DLNA media server on Windows 8

You can share media stream over network using Windows Media Player. But it is not available by default. So, in order to enabling this feature, you need to open Windows Media Player and select Stream menu. Then, it will open Media streaming options. So select Turn on media streaming button. You can list which DLNA devices are available on the same network. Select the one you want to share with and then press OK. Note that you also can select specific devices can access only specific folders from your Libraries.

Rename Network in Windows 8

Take a look on:http://superuser.com/questions/550178/how-can-i-rename-a-network-in-windows-8.

Open regedit and edit the following of these registry keys:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Nla\Cache\Intranet
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Profiles
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkList\Signatures\Unmanaged

Friday, February 28, 2014

Access shared network from Windows Command Prompt

To access network shared folder from Command Prompt, it cannot use cd command. In order to access shared folders, we need to mount it as a new drive by run the following command:
// Method 1
net use [drive letter]\\[machine]\[folder]
// Method 2
pushd \\[machine]\[folder]

// Example 1
net use z: \\machine_name\shared_folder_name
// List folders on shared drive
dir net use z:

// Example 2
pushd \\machine_name\shared_folder_name
Both methods can do the same things, but the different is the second method will allocate and change current directory to the new drive automatically by the allocated drive is started from unused reversed alphabetical order.
To remove mounted drive, we can use the following command to delete it.
net use [drive letter] /delete

// Example
net use z: /delete

Friday, February 15, 2013

Change IE security setting to normal in Windows Server 2012

By default Internet Explorer (IE) in Windows Server is protected with some security to prevent unintentionally attacked during browse internet. Sometimes, we want it to be just a normal IE that trusts how user use it. In order to do that in Windows Server 2012 is described as follows:

Firstly, opens Server Manager page.


Next, on the top of Dashboard under welcoming message, clicks at "Configure this local server" as shown picture below.

Then, on properties tab, you will see information is divided into 2 sides. Look at the right side. You will see "IE Enhanced Security Configuration", it should be on if your IE is still protected. So, we gonna change it off. by click at it.

After you click it, a popup will be opened. Your job is changing to off as shown below.

Click OK and wait for a while during system setting is changing. When it finished, you will notice on properties tab "IE Enhanced Security Configuration" is changed to Off.

Thursday, February 14, 2013

Remove Remote Desktop Entries from Remote Desktop Connection

Steps to remove are described as follows:
  1. Click start or press Windows button, it will show application screen.
  2. Type "regedit", it will search and show only one program.
  3. Select that "regedit.exe".
  4. On the left hand side of the program, it is a navigation panel. Then you can easily navigate to "HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default".
  5. On the right hand side of the program, they are entries of all connection Remote Desktop Connection remembered. In order to remove an entry, just select which connection you want to delete using right click at its name then select delete command. It will automatically remove (no need to save again).
Reference: http://support.microsoft.com/kb/312169

Sunday, January 27, 2013

Image POST Client and Sever in Python and C#

From last time, I had told how to encode image into base64 string[1], and how to do POST message to HTTP server[2][3] This post will continue from those posts. First, we will create HTTP POST server in Python. I based on the concept that a message will be encoded using url-encode format in a form of base64 string, and the image string will be sent to a variable named "img". It will decode an image string from that variable.
import SimpleHTTPServer
import SocketServer
import cgi
from base64 import decodestring

PORT = 8000

class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

 def _writeheaders(self):
  self.send_response(200)
  self.send_header('Content-type', 'text/html')
  self.end_headers()

 def do_GET(self):
  filename = 'temp.png'
  f = open(filename, 'rb')
  encode = f.read().encode('base64')
  img = '<img height="200" src="data:image/png;base64,' + encode + '" width="250" />'
  self._writeheaders()
  self.wfile.write("""
  <html><head><title>Simple Server</title></head>
   <body>
    It worked!!!!
 
    %s
   </body>
  </html>"""  % (img))
 def do_POST(self):
  form = cgi.FieldStorage(
   fp=self.rfile,
   headers=self.headers,
   environ={'REQUEST_METHOD':'POST',
      'CONTENT_TYPE':self.headers['Content-Type'],
     })
  encode = form['img'].value
  decode = decodestring(encode)
  output = open('temp.png', 'wb')
  output.write(decode)
  output.close()
  # After posting image has done, it will response GET message to show that image
  self.do_GET()

Handler = ServerHandler

httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()
Then, we will create HTTP POST client to upload an image to our HTTP POST server.
Python:
import urllib, urllib2

uri = 'http://localhost:8000'
filename = 'Leafa.jpg'
f = open(filename, 'rb')
encode = f.read().encode('base64')
params = { 'img' : encode }
data = urllib.urlencode(params)

p = urllib2.urlopen(uri, data)
print p.read()
C# WPF:
string fileName = "Leafa.jpg";
StreamResourceInfo sri = null;
Uri uri = new Uri(fileName, UriKind.Relative);
sri = Application.GetResourceStream(uri);

using (var memoryStream = new MemoryStream())
{
    sri.Stream.CopyTo(memoryStream);
    byte[] result = memoryStream.ToArray();
    var base64 = "img=" + HttpUtility.UrlEncode(System.Convert.ToBase64String(result));

    MessageBox.Show(base64);

    using (var wc = new WebClient())
    {
        wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
        wc.UploadStringCompleted += wc_UploadStringCompleted;
        wc.UploadStringAsync(new Uri(url), "POST", base64);
    }
}
The server will response a web page, which the client will show that response as a text format, so, if you want to make sure that your image are already uploaded, just check it the "server.py" directory. You will see the image named "temp.png", which is converted from jpg image in the client side. Moreover, you can use a web browser request to http://localhost:8000 to let GET response show you that uploaded one.

The sample project is uploaded, can download from http://www.mediafire.com/?1okv3lc6nk1jsc7.

Leafa.jpg
References:
  1. Encode an Image into base64 string in C# / Python
  2. Simple HTTP POST Server / Client with Python
  3. HTTP POST data via WebClient and WebRequest

Tuesday, January 15, 2013

Double NAT - How to solve it?

Before I going to explain how to solve double NAT problem, I will introduce what is NAT first. Due to the number of IP addresses on internet is limited, NAT (Network Address Translation) was introduced. A router will use only one public IP address (Gateway), however, a network behind NAT is using private IP addresses, which is valid within the router network. To be able to access a network within NAT, port forwarding is required in order to bypass the public IP address with a specific port to a specific private IP address with specific port as well. This scenario represents a single level of NAT, having only one router cover all the entire network. But it often isn't simple like this.

Double NAT is a scenario where multiple routers on network do network address translation. The most common sample is a Cable or DSL modem is connected to a Wi-Fi router. NAT of both modem and router are enabled. Then, computers on the network are connected to the Wi-Fi router. In this scenario, even if port forwarding is setup on the Wi-Fi router, the computer will not be accessible from internet because the Wi-Fi doesn't have a public IP address. It has only a private IP address, which is given from the Cable/DSL modem. There are many solutions to solve this problem, however, there is no silver bullet. It depends on situation which one is suitable.

Possible Solutions: 

1. Setup PPPoE connection between the wireless router and modem 

This is the most robust solution, unfortunately not all ISPs provide enough information for this to be setup easily 

PPPoE can be usually setup in the wireless router's WAN settings. There are usually multiple options to configure the WAN connection of wireless router, amongst which are DHCP and PPPoE. DHCP is no good here, as it results in private IP address assigned to the WiFi router. PPPoE is better, because it bypasses the NAT in the modem, however it might need login and password information which the ISP might not provide.

2. Put the wireless router in bridged mode 

Bridged mode on wireless router means that NAT and DHCP functions on it will be disabled. Some router call it bridged mode, some simply allow you to disable NAT and DHCP. Unfortunately some WiFi routers simply don't support bridged mode at all. 

If you manage to switch router to bridged mode, all port forwarding needs to be configured on the modem (either automatically if it supports NAT-PMP, or manually).

3. Put the wireless router in modem's DMZ 

DMZ (demilitarized zone) is a common feature of router that allow to chose one client to which all traffic is forwarded. If your modem supports DMZ, this might be solution for you: 

1. Find out the WAN address of wireless router. For this you might need to log in to the WiFi router admin interface and look at the Status page (most router's have status pages which show relevant information about the WAN connection). 

2. Log in to the modem web administration interface, find the DMZ settings and put the WiFi router's IP WAN address there. 

Note that with this solution you will still get a double NAT warning in Air Video Server, but if the port forwarding on Wireless router is setup correctly, things should work.

4. Forward the port 45631/TCP in the modem to the router

This solution is similar to [3], except that instead of putting the WiFi router to modem's DMZ only one port is forwarded. 

1. Find out the WAN address of wireless router. For this you might need to log in to the WiFi router admin interface and look at the Status page (most router's have status pages which show relevant information about the WAN connection). 

2. Login in the modem web admin interface and configure port forwarding of port 45631 (protocol TCP) to the address from router's status page.

Note that with this solution you will still get a double NAT warning in Air Video Server.

From mentioned solutions, for me, I prefer to use the first two solutions because they are easy to setup, just setting either a DSL/Cable modem or Wi-Fi router to a bridged mode. The  two nested networks will become one. It is different only in setting DSL/Cable modem or router to a bridged mode is needed to use a Wi-Fi router connecting to ISP using PPPoE with username and password, but setting a Wi-Fi router to a bridged mode, the DSL/Cable modem or router must be able to set port forwarding, which in some routers there is only one direction from in to out, doesn't allow outside network coming in.

Reference: http://inmethod.com/forum/posts/list/908.page -> This thread helps me so much, thanks to him.

Friday, November 30, 2012

Simple HTTP POST Server / Client with Python

Continue from the last post, it's about simple HTTP server with Python. Today, I will explain more about create POST server with Python. From last time to response GET request, we need to override do_GET in class SimpleHTTPRequestHandler. Similarly, to response POST request, we just override do_POST method. However, to receive parameters from POST there are 2 popular formats: url-encode, and multipart as I described in my previous post

In this post I will describe only url-encode. It's like encrypt the data in url format before sending to the server. So, your data will be like "{key1}={value1}&{key2}={value2} ...:". Basically, it's not that difficult with Python because all we need, are already had.

HTTP POST Client:
import urllib, urllib2

uri = 'http://localhost:8000'
name = "Mark"
# Encode data in base64 string
encode = name.encode('base64')
params = { 'name' : encode }
# Pack key-value pairs in form of url-encode format
data = urllib.urlencode(params)

# urlopen with data will use POST method by default
p = urllib2.urlopen(uri, data)
print p.read()
HTTP POST Server:
import SimpleHTTPServer
import SocketServer
import cgi
from base64 import decodestring

# Server port
PORT = 8000

class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
  
        def do_POST(self):
                # Use cgi module to retrieve data from POST as a form
                form = cgi.FieldStorage(
                        fp=self.rfile,
                        headers=self.headers,
                        environ={'REQUEST_METHOD':'POST',
                                 'CONTENT_TYPE':self.headers['Content-Type'],
                                 })
                # We can get value from the form key like we did in dictionary class
                encode = form['name'].value
                # Decide the value from base64 string
                decode = decodestring(encode)
                self.wfile.write('Hello, ' + decode + '.')
                
Handler = ServerHandler

# Initialize server object
httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()

Wednesday, November 28, 2012

Simple HTTP Server with Python

To create HTTP server in Python, we need to bind to a port & IP address, listen to that port for responding requests. To do that, we can use built-in module named BaseHTTPServer to handle HTTP requests. The main methods are do_GET and do_HEAD, we will need them to construct our header and body.

Here is a server code:
import SimpleHTTPServer
import SimpleHTTPServer
import SocketServer

# Server port
PORT = 8000

class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):

 def _writeheaders(self):
  self.send_response(200)
  self.send_header('Content-type', 'text/html')
  self.end_headers()

 def do_GET(self):
  # Handle GET request
  self._writeheaders()
  self.wfile.write("""
  <html><head><title>Simple Server with Python</title></head>
   <body>
    Hello World!!!!
   </body>
  </html>""")

Handler = ServerHandler

# Initialize server object
httpd = SocketServer.TCPServer(("", PORT), Handler)

print "serving at port", PORT
httpd.serve_forever()
For handling POST request, just create do_POST method in ServerHandler class. I will explain more in the next post. For this post, just want to ground the basic HTTP server knowledge.

References:

Monday, November 26, 2012

HTTP POST data via WebClient and WebRequest

To request HTTP with POST method in .NET, there are 2 classes applicable to do that: WebClient, and WebRequest. I will describe  both ways in post. Normally to send the data back via POST method, there are 2 kinds of content-type (that I know) are url-encode, multipart. These two content types have an effect for the specific format for a receiver and how to construct a form message. In this post I will explain only url-encode. Firstly, we should know how to construct a format. For urlencode format, the format is very similar to querystring format like "{key1}={value1}&{key2}={value2}...". Moreover, we should encode the values like a GET parameter string (not necessary but for some characters, they need to).

To specific content-type for urlencode is set its value to "application/x-www-form-urlencoded".

Example 1: using WebClient
using System.Web;
...
private void wc_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
     // Show a return message when upload is completed
     var result = (string)e.Result;
     MessageBox.Show(result);
}

private void Do_Something()
{
      string name = "Hello";
      string url = "<host ip>";
      var base64 = "name=" + HttpUtility.UrlEncode(result);

      var wc = new WebClient();
      wc.Headers["Content-Type"] = "application/x-www-form-urlencoded";
      wc.UploadStringCompleted += wc_UploadStringCompleted;
      wc.UploadStringAsync(new Uri(url), "POST", base64);
}
Example 2: using WebRequest
using System.Net;
...
private void Do_Something()
{
      string name = "Hello";
      string url = "<host ip>";
      var base64 = "name=" + HttpUtility.UrlEncode(result);

      var encode = Encoding.UTF8.GetBytes(base64);

      var request = WebRequest.Create(new Uri(url));
      request.Method = "POST";
      request.ContentType = "application/x-www-form-urlencoded";
      request.ContentLength = encode.Length;
      Stream dataStream = request.GetRequestStream();
      dataStream.Write(encode, 0, encode.Length);
      dataStream.Close();

      using (var response = request.GetResponse())
      {
           using (var reader = new StreamReader(response.GetResponseStream()))
           {
                // Show a response message
                string responseText = reader.ReadToEnd();
                MessageBox.Show(responseText );
            }
      }
}
The different from these 2 methods in my opinion are details for handling data i.e. We need to create delegate function for handling task when uploading is done, but WebRequest doesn't need to. Moreoever, WebClient has higher level of data sending compared to WebRequest. WebRequest need to pack data into byte array, but WebClient can send them as a pack of string directly.

Friday, November 23, 2012

What the different between Web Browser, Web Client, WebRequest, WebResponse

I found the answer from stack overflow. He said as the following description:
WebBrowser is actually in the System.Windows.Forms namespace and is a visual control that you can add to a form. It is primarily a wrapper around the Internet Explorer browser (MSHTML). It allows you to easily display and interact programmatically with a web page. You call the Navigate method passing a web URL, wait for it to complete downloading and display and then interact with the page using the object model it provides.

HttpWebRequest is a concrete class that allows you to request in code any sort of file over HTTP. You usually receive it as a stream of bytes. What you do with it after that is up to your application.

HttpWebResponse allows you to process the response from a web server that was previously requested using HttpWebRequest.

WebRequest and WebResponse are the abstract base classes that the HttpWebRequest and HttpWebResponse inherit from. You can't create these directly. Other classes that inherit from these include Ftp and File classes.

WebClient I have always seen as a nice helper class that provides simpler ways to, for example, download or upload a file from a web url. (eg DownloadFile and DownloadString methods). I have heard that it actually uses HttpWebRequest / HttpWebResponse behind the scenes for certain methods.

If you need more fine grained control over web requests and responses, HttpWebRequest / HttpWebResponse are probably the way to go. Otherwise WebClient is generally simpler and will do the job.
In my opinion, I prefer to use WebClient because it's much more higher level, and easy to use in case we need to specific setting parameters. However, if I only use it for crawl data, mostly I just use WebRequest because it's short, and simple don't need to have delegate for async function.

Reference: http://stackoverflow.com/questions/1780679/net-webbrowser-webclient-webrequest-httpwebrequest-argh

Monday, November 5, 2012

Crawl HTTP 403 Forbidden Error page (may solve)

Sometime, to crawl specific page, the web servers may block you crawl their contents using a simple method by looking at UserAgent header request from a client request. In well-known web clients like IE, FireFox, Chrome, Opera, those clients are trusted by anyone, so servers will allows them to access the contents. Specific programs, however, won't be allowed to do that just because they don't have signature for it. To solve this program, you can add UserAgent header into that program using signature from well-known web clients. In case that servers block for specific clients to prevent some bots that don't have UserAgent header,  This way is the easiest solution.

The following code is an example of adding UserAgent header in C#:
HttpWebRequest request = (HttpWebRequest)WebRequest.CreateDefault(uri);
request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.0.6) Gecko/20060728 Firefox/1.5";
And this is an example code for Python:
import urllib2
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
ob = opener.open('http://www.google.com/')
print ob.read()

Thursday, September 13, 2012

Setting Router (DD-WRT) as a client in unbridged mode

This a a Linksys router (DD-WRT), I just borrowed to configure it as a client hahaha. I mean config this router to connect main router ( has WAN) via wireless network, then make computers and client router connect together via LAN.

To set it up do as follows:
  • Change router mode (in wireless tab) to client mode, and set SSID to be the same as main router's SSID.
  • In wireless security tab (sub tab), set security mode and password to be the same as main router's also.
  • In security tab, disable firewall because it will make your setting become harder to be set. You can configure later if you want to.
  • In setup tab, change connection type to Automatic Configuration - DHCP, and disable STP.
  • Change router IP, which is different from main router IP. e.g. if your main router IP is 192.168.1.*, you can change a client router IP to 192.168.2.*. Next, use the same subnet mask.
  • Check at Use DNSMasq for DHCP.
  • Check at use DNSMasq for DNS.
  • Check at DHCP-Authoritative.
  • Set other stuffs if necessary.

Sunday, June 17, 2012

How to configure FTP Server in Windows Server 208 R2



After that, you may need to config the Passive Port Range for FTP Service which you can follow this instruction. It will show you steps, and explain what they are.

Thursday, December 1, 2011

Benchmark of Python WSGI Web Servers

Take a look this site, http://nichol.as/benchmark-of-python-web-servers. He tried his best to benchmark the different WSGI servers. He presented in graphs to make easy understanding.

Monday, November 28, 2011

Run internet required commands behind a proxy server in Linux

Most of the time I need to run a terminal behind a proxy server at my office to run a batch job, and I failed to run it because I don't know how to add proxy server in the terminal. But, now, I just found the command to add a proxy server in Linux. It's very simple just only one line :)

Open terminl and type this command
# Changing username, password, proxyname, and port to be yours.
export http_proxy="http://username:password@proxyname:port"
# After that you can test to run behind your proxy server
# , simply as following.
wget http://www.google.com
# If the connection is successful, then you will get the 
# file from this Google page.

To remove the proxy server from your network run the following command:
# Just delete a proxy sever variable using unset 
unset http_proxy
# Or set http_proxy to blank
export http_proxy=""

The example above is how bind a proxy server in HTTP protocol.
For the other protocols, e.g. FTP, ... so on. Try to find its variable for binding with a proxy server.
Another protocol that I know is FTP.
FTP => ftp_proxy
If you want to remove it, do the same as the example above.

Good luck ^^.

How to restart Linux network service

Sometime you may need to update your network immediately, e.g. DHCP and IP under a virtualization software, ... so on. The fastest way is to restart the network service.

You need to login as root user before using the following commands!!!

RedHat Linux command to reload or restart network:
# To restart Linux network service:
$ service network restart
or
$ /etc/init.d/network restart

# To start Linux network service:
$ service network start

# To stop Linux network service:
$ service network stop
Debian Linux command to reload or restart network:
# To restart Linux network service:
$ /etc/init.d/networking restart

# To start Linux network service:
$ /etc/init.d/networking start

# To stop Linux network service:
$ /etc/init.d/networking stop
Ubuntu Linux user use sudo command with above Debian Linux command:
# To restart Linux network service:
$ sudo /etc/init.d/networking restart

# To start Linux network service:
$ sudo /etc/init.d/networking start

# To stop Linux network service:
$ sudo /etc/init.d/networking stop

Credit: http://theos.in/desktop-linux/tip-that-matters/how-do-i-restart-linux-network-service/