Showing posts with label example code.Networking. Show all posts
Showing posts with label example code.Networking. Show all posts

Saturday, June 3, 2017

Python to get ssid and IP address

Python example to get the ssid of connected network, and my IP address. Work on both Python 2 and 3.

pyWireless.py
import os

#'\' is used to splite pythone line
ipaddress = os.popen("ifconfig wlan0 \
                     | grep 'inet addr' \
                     | awk -F: '{print $2}' \
                     | awk '{print $1}'").read()
ssid = os.popen("iwconfig wlan0 \
                | grep 'ESSID' \
                | awk '{print $4}' \
                | awk -F\\\" '{print $2}'").read()

print("ssid: " + ssid)
print("ipaddress: " + ipaddress)



remark:
The ssid should have no space, otherwise the parts after space will be missed.

Tested on Raspberry Pi 2 with WiFi dongle.

Sunday, May 29, 2016

Java Datagram/UDP Server and Client, run on raspberry Pi


A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed. It's simple exampls of Datagram/UDP Client and Server, modified from Java Tutorial - Writing a Datagram Client and Server.

It's assumed both server and client run on the same Raspberry Pi, so the IP is fixed "127.0.0.1", local loopback. And the port is arbitrarily chosen 4445.


In the Server side, JavaUdpServer.java, creates a DatagramSocket on port 4445. Wait for client connect, and reply with current date/time.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Date;

/*
reference:
https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
*/
public class JavaUdpServer {
    
    static UdpServerThread udpServerThread;

    public static void main(String[] args) throws IOException {
        System.out.println("Server start");
        System.out.println("Runtime Java: " 
                + System.getProperty("java.runtime.version"));
        
        
        new UdpServerThread().start();
    }

    private static class UdpServerThread extends Thread{
        
        final int serverport = 4445;
        
        protected DatagramSocket socket = null;
        
        public UdpServerThread() throws IOException {
            this("UdpServerThread");
        }
        
        public UdpServerThread(String name) throws IOException {
            super(name);
            socket = new DatagramSocket(serverport);
            System.out.println("JavaUdpServer run on: " + serverport);
        }

        @Override
        public void run() {
            
            while(true){
                
                try {
                    byte[] buf = new byte[256];
                    
                    // receive request
                    DatagramPacket packet = new DatagramPacket(buf, buf.length);
                    socket.receive(packet);
                    
                    String dString = new Date().toString();
                    buf = dString.getBytes();
                    
                    // send the response to the client at "address" and "port"
                    InetAddress address = packet.getAddress();
                    int port = packet.getPort();
                    System.out.println("Request from: " + address + ":" + port);
                    packet = new DatagramPacket(buf, buf.length, address, port);
                    socket.send(packet);
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
                
            }
            
        }
        
    }
    
}


In the client side, JavaUdpClient.java, sends a request to the Server, and waits for the response.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

/*
reference:
https://docs.oracle.com/javase/tutorial/networking/datagrams/clientServer.html
*/
public class JavaUdpClient {

    public static void main(String[] args) 
            throws UnknownHostException, SocketException, IOException {
        
        //Hardcode ip:port
        String ipLocalLoopback = "127.0.0.1";
        int serverport = 4445;
        
        
        System.out.println("Runtime Java: " 
                + System.getProperty("java.runtime.version"));
        System.out.println("JavaUdpClient running, connect to: " 
                + ipLocalLoopback + ":" + serverport);
        
        // get a datagram socket
        DatagramSocket socket = new DatagramSocket();
        
        // send request
        byte[] buf = new byte[256];
        InetAddress address = InetAddress.getByName(ipLocalLoopback);
        DatagramPacket packet = 
                new DatagramPacket(buf, buf.length, address, serverport);
        socket.send(packet);
        
        // get response
        packet = new DatagramPacket(buf, buf.length);
        socket.receive(packet);
        
        String received = new String(packet.getData(), 0, packet.getLength());
        System.out.println(received);
        
        socket.close();
    }
    
}


Related:
- Android version Datagram/UDP Client
Android version Datagram/UDP Server

Monday, May 23, 2016

Java Network exercise: client and server - client send something to server

Refer to my old post of "Java exercise - Implement client and server to communicate using Socket", setup bold server and client. The server reply something to client once connected.


It's modified, client connect to server and send something. In server side, wait connected and print the received text to screen.


host.java
import java.io.BufferedReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;

class host
{
    public static void main(String srgs[])
    {   
        ServerSocket serverSocket = null;
        Socket socket = null;
        BufferedReader bufferedReader = null;
        PrintStream printStream = null;
        
        try{
            serverSocket = new ServerSocket(0);
            System.out.println("I'm waiting here: " 
                + serverSocket.getLocalPort());            
                                
            socket = serverSocket.accept();
            System.out.println("from " + 
                socket.getInetAddress() + ":" + socket.getPort());
            
            InputStreamReader inputStreamReader = 
                new InputStreamReader(socket.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader);
            
            String line;
            while((line=bufferedReader.readLine()) != null){
                System.out.println(line);
            }
        }catch(IOException e){
            System.out.println(e.toString());
        }finally{
            if(bufferedReader!=null){
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    System.out.print(ex.toString());
                }
            }
            
            if(printStream!=null){
                printStream.close();
            }
            
            if(socket!=null){
                try {
                    socket.close();
                } catch (IOException ex) {
                    System.out.print(ex.toString());
                }
            }
        }
    }
}


client.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class client {

    public static void main(String args[])
    { 
        if(args.length != 2){
            System.out.println("usage: java client <port> <something>");
            System.exit(1);
        }
        
        int port = isParseInt(args[0]);
        if(port == -1){
            System.out.println("usage: java client <port> <something>");
            System.out.println("<port>: integer");
            System.exit(1);
        }
        
        try{
            //IP is hard coded, Local Loopback = "127.0.0.1"
            //port is user entry
            Socket socket = new Socket("127.0.0.1", port);

            
            //Send msg to server
            OutputStream outputStream = socket.getOutputStream();
            PrintStream printStream = new PrintStream(outputStream);
            printStream.print(args[1]);
                
            socket.close();

        }catch(UnknownHostException e){
            System.out.println(e.toString());
        }catch(IOException e){
            System.out.println(e.toString());
        }

    }
    
    private static int isParseInt(String str){
        
        int num = -1;
        try{
             num = Integer.parseInt(str);
        } catch (NumberFormatException e) {
        }
        
        return num;
    }
    
}


It's Android version of the Client.

Next:
- bi-direction communication, between echo server and client

Sunday, February 7, 2016

c language to get MAC address, run on Raspberry Pi/Raspbian Jessie


c language to get MAC address, run on Raspberry Pi/Raspbian Jessie:


reference: http://www.geekpage.jp/en/programming/linux-network/get-macaddr.php

cMAC.c
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>

int
main()
{
    int fd;
    struct ifreq ifr;
    
    fd = socket(AF_INET, SOCK_DGRAM, 0);
    
    ifr.ifr_addr.sa_family = AF_INET;
    strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
    
    ioctl(fd, SIOCGIFHWADDR, &ifr);
    close(fd);
    
    printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
        (unsigned char)ifr.ifr_hwaddr.sa_data[0],
        (unsigned char)ifr.ifr_hwaddr.sa_data[1],
        (unsigned char)ifr.ifr_hwaddr.sa_data[2],
        (unsigned char)ifr.ifr_hwaddr.sa_data[3],
        (unsigned char)ifr.ifr_hwaddr.sa_data[4],
        (unsigned char)ifr.ifr_hwaddr.sa_data[5]);
        
    return 0;
}


Related:
Java to list Network Interface Parameters (include MAC address)
Python to get MAC address using uuid

Monday, September 14, 2015

Java example - scan connected IP in the same network

Last post advise use Advanced IP Scanner to scan connected host in the same network. Here is a Java example to scan connected IP in the same network, using isReachable(int timeout) method of java.net.InetAddress.


public boolean isReachable(int timeout) throws IOException

Test whether that address is reachable. Best effort is made by the implementation to try to reach the host, but firewalls and server configuration may block requests resulting in a unreachable status while some specific ports may be accessible. A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will try to establish a TCP connection on port 7 (Echo) of the destination host.

The timeout value, in milliseconds, indicates the maximum amount of time the try should take. If the operation times out before getting an answer, the host is deemed unreachable. A negative value will result in an IllegalArgumentException being thrown.


JavaIpScanner.java
package javaipscanner;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JavaIpScanner {

    /*
    Example to scan ip 192.168.1.100~120
    check if any ip is reachable, means connected host
    */
    static final String SUB_NET = "192.168.1.";

    public static void main(String[] args) {
        scanHost(SUB_NET, 100, 120);
    }

    private static void scanHost(String subnet, int lower, int upper) {
        final int timeout = 3000;

        for (int i = lower; i <= upper; i++) {
            String host = subnet + i;
            try {
                InetAddress inetAddress = InetAddress.getByName(host);
                
                if (inetAddress.isReachable(timeout)){
                    System.out.println(inetAddress.getHostName() 
                            + " isReachable");
                    System.out.println(inetAddress.toString());
                    System.out.println("--------------------");
                }
                
            } catch (UnknownHostException ex) {
                Logger.getLogger(JavaIpScanner.class.getName())
                        .log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(JavaIpScanner.class.getName())
                        .log(Level.SEVERE, null, ex);
            }
        }
    }

}



Related:
- Android version Scan Reachable IP to discover devices in network

Friday, December 20, 2013

Java exercise - Client and Server example III, run socket operation in background thread

This exercise implement socket operation of host in background thread, modify from last exercise, "ServerSocket stay in loop".

run socket operation in background thread
run socket operation in background thread
host.java
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class host {

    public static void main(String srgs[]) {

        int count = 0;

        //hard code to use port 8080
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            
            System.out.println("I'm waiting here: " + serverSocket.getLocalPort());
            
            while (true) {
                
                try {
                    Socket socket = serverSocket.accept();
                            
                    count++;
                    System.out.println("#" + count + " from "
                            + socket.getInetAddress() + ":" 
                            + socket.getPort());
                    
                    /*  move to background thread
                    OutputStream outputStream = socket.getOutputStream();
                    try (PrintStream printStream = new PrintStream(outputStream)) {
                        printStream.print("Hello from Raspberry Pi, you are #" + count);
                    }
                    */
                    HostThread myHostThread = new HostThread(socket, count);
                    myHostThread.start();
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }
    
    private static class HostThread extends Thread{
        
        private Socket hostThreadSocket;
        int cnt;
        
        HostThread(Socket socket, int c){
            hostThreadSocket = socket;
            cnt = c;
        }

        @Override
        public void run() {

            OutputStream outputStream;
            try {
                outputStream = hostThreadSocket.getOutputStream();
                
                try (PrintStream printStream = new PrintStream(outputStream)) {
                        printStream.print("Hello from Raspberry Pi in background thread, you are #" + cnt);
                }
            } catch (IOException ex) {
                Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
            }finally{
                try {
                    hostThreadSocket.close();
                } catch (IOException ex) {
                    Logger.getLogger(host.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }
}


Keep using the client.java in last exercise of "client and server to communicate using Socket".

Tuesday, December 17, 2013

Java exercise - Client and Server example II, ServerSocket stay in loop

In the previous exercise of "client and server to communicate using Socket", the host.java stay waiting request from client.java, and terminate after responsed. In this step, it's modified to stay in loop, for next request; until user press Ctrl+C to terminate the program.

host stey in loop
host stey in loop, until Ctrl+C.

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;

public class host {

    public static void main(String srgs[]) {

        int count = 0;

        //hard code to use port 8080
        try (ServerSocket serverSocket = new ServerSocket(8080)) {
            System.out.println("I'm waiting here: " 
                + serverSocket.getLocalPort());
            
            System.out.println(
                "This program will stay monitoring port 80.");
            System.out.println(
                "Until user press Ctrl+C to terminate.");
            
            while (true) {
                try (Socket socket = serverSocket.accept()) {
                    count++;
                    System.out.println("#" + count + " from "
                            + socket.getInetAddress() + ":" 
                            + socket.getPort());
                    OutputStream outputStream = socket.getOutputStream();
                    try (PrintStream printStream = 
                        new PrintStream(outputStream)) {
                            printStream.print(
                                "Hello from Raspberry Pi, you are #" 
                                + count);
                    }
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }
}

Keep using the client.java in last exercise of "client and server to communicate using Socket".



Next exercise: - Client and Server example III, run socket operation in background thread.