- package com.cust.util;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- import java.io.Writer;
- import java.net.DatagramSocket;
- import java.net.InetAddress;
- import java.net.MalformedURLException;
- import java.net.SocketException;
- import java.net.URL;
- import java.net.URLConnection;
- import java.net.UnknownHostException;
- /**
- * java net demo
- * @author lee
- *
- */
- public class IpTest {
- String url = "http://www.163.com";//读取的网址
- String path = "D:/code.html";//网页代码保存到本地路径、名称
- /**
- * 读取本机ip信息
- */
- public void ipconfig() {
- try {
- InetAddress inet = InetAddress.getLocalHost();
- System.out.println("ip地址:"+inet.getHostAddress()+"/"+"名称" + inet.getHostName());
- } catch (UnknownHostException e) {
- e.printStackTrace();
- }
- }
- /**
- * 读取网页源码,保存到本地
- */
- public void UrlTest() {
- try {
- System.out.println("starting.....");
- int c;
- URL u = new URL(url);//获取地址
- URLConnection urlc = u.openConnection();//建立连接
- InputStreamReader ist = new InputStreamReader(
- urlc.getInputStream(), "GB2312");//获得流
- FileOutputStream fw = new FileOutputStream(path);//输出文件流
- Writer w = new OutputStreamWriter(fw, "GB2312");
- System.out.println(urlc.getContentEncoding());
- System.out.println(urlc.getContentType());
- while ((c = ist.read()) != -1) {
- w.write((char) c);//保存到本地
- System.out.print((char) c);//控制台输出
- }
- //关闭流
- fw.close();
- ist.close();
- } catch (MalformedURLException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * UDP,通过DatagramSocket的异常查看被占用的端口
- */
- public void UDPTest() {
- System.out.println("查看中......");
- for (int port = 0; port <= 65535; port++) {
- try {
- DatagramSocket ds = new DatagramSocket(port);
- // System.out.println("端口" + port + "未被占用");
- ds.close();
- } catch (SocketException e) {
- System.out.println("端口" + port + "被占用");
- }
- }
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- IpTest ip = new IpTest();
- ip.ipconfig();
- ip.UrlTest();
- ip.UDPTest();
- }
- }
最简单的网络编程代码,ip、url、UDP
最新推荐文章于 2024-06-28 12:16:08 发布