平台
RK3288 + Android 7.1
问题
android 应用无法绑定 < 1024 的端口号.
void tryBind80Port(){ new Thread(){ @Override public void run() { try { InetSocketAddress addr = new InetSocketAddress(80);//以80测试 ServerSocket ss = new ServerSocket(); ss.bind(addr); } catch (IOException e) { e.printStackTrace(); } } }.start(); }
报错LOG
2017-01-01 20:03:11.998 2762-2778/com.ansondroider.appshortcut W/System.err: java.net.BindException: Permission denied 2017-01-01 20:03:11.998 2762-2778/com.ansondroider.appshortcut W/System.err: at java.net.PlainSocketImpl.socketBind(Native Method) 2017-01-01 20:03:11.998 2762-2778/com.ansondroider.appshortcut W/System.err: at java.net.AbstractPlainSocketImpl.bind(AbstractPlainSocketImpl.java:368) 2017-01-01 20:03:11.998 2762-2778/com.ansondroider.appshortcut W/System.err: at java.net.ServerSocket.bind(ServerSocket.java:377) 2017-01-01 20:03:11.998 2762-2778/com.ansondroider.appshortcut W/System.err: at java.net.ServerSocket.bind(ServerSocket.java:331) 2017-01-01 20:03:11.998 2762-2778/com.ansondroider.appshortcut W/System.err: at com.ansondroider.appshortcut.MainActivity$1.run(MainActivity.java:39)
解决
参考:https://www.linuxquestions.org/questions/linux-networking-3/allowing-non-root-to-bind-to-ports-1024-a-350437/
//kernel/include/net/sock.h /* Sockets 0-1023 can't be bound to unless you are superuser */ #define PROT_SOCK 1024
文件中已声明, 0 - 1023 端仅 SU用户能使用. 所以, 修改的方法只是也是把限制的端口号改低或直接改为0.
PS: 个人并不建议去修改这个端口号, 最好还是APP能够申请其它端口, 这样也会少一些冲突